Multi-Stock Trading Bot Using Guppy Strategy with 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.

Objective

In our latest trading bot, we unveil an advanced trading bot, a leap forward in both complexity and functionality:

  • Advanced Trading Strategy: This bot is finely tuned to initiate buy trades when the indicator flashes a green signal and to execute sell orders upon a red signal. This sophisticated approach ensures dynamic and responsive trading actions based on real-time market signals.

  • Multi-Stock Capability: Breaking away from the limitations of its predecessors, this bot is adept at handling multiple stocks concurrently. This feature marks a significant advancement over previous models which were confined to trading a single stock at a time.

  • Comprehensive Market Scanning: The bot is engineered to continuously scan all stocks within the Nifty 50 index. It intelligently executes and manages trades for any stock that aligns with the defined buy or sell criteria.

  • Ongoing Monitoring: Unlike earlier versions, this bot maintains an ongoing surveillance of the entire stock list. This continuous monitoring ensures that no potential trading opportunity is missed, and allows for swift action in a fast-moving market environment.

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

				
					sdate = (date.today() - timedelta(days=15)).strftime("%Y-%m-%d")
todate = date.today().strftime("%Y-%m-%d")

while 1:
    ks=str(input("nifty or fno ?")).upper()
    if ks=="NIFTY":
        tokenall=[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]
        ss=['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']
        break
    if ks=="FNO":
        tokenall=[5633, 6401, 3861249, 4451329, 2760193, 20993, 325121, 2524673, 41729, 49409, 54273, 60417, 70401, 1510401, 1195009, 1214721, 94977, 108033, 2714625, 2911489, 2763265, 3812865, 160001, 160769, 163073, 177665, 5215745, 3876097, 197633, 3771393, 225537, 173057, 261889, 1207553, 3463169, 2796801, 315393, 3378433, 2513665, 1850625, 340481, 341249, 3789569, 345089, 2747905, 348929, 359937, 356865, 364545, 3699201, 1270529, 377857, 3677697, 3060993, 381697, 2883073, 387073, 387841, 1346049, 408065, 2393089, 415745, 3920129, 424961, 1723649, 2661633, 2933761, 3011329, 4574465, 3001089, 4632577, 492033, 2061825, 511233, 2939649, 2672641, 519937, 2815745, 2674433, 582913, 593665, 3924993, 2977281, 2748929, 633601, 2819073, 636673, 2730497, 3834113, 2906881, 3364353, 731905, 3375873, 3930881, 737793, 738561, 141569, 3078657, 779521, 780289, 1492737, 1522689, 1102337, 857857, 3431425, 3076609, 1837825, 871681, 952577, 878593, 884737, 4343041, 877057, 895745, 2953217, 3465729, 897537, 2873089, 2952193, 2752769, 920065, 951809, 3026177, 969473, 3050241, 112129, 134657, 3721473, 2800641, 3385857, 4454401, 1152769, 806401, 617473, 2905857, 3660545, 3906305, 758529, 975873]
        ss=['ACC', 'ADANIENT', 'ADANIPORTS', 'ADANIPOWER', 'ALBK', 'ALOKTEXT', 'AMBUJACEM', 'ANDHRABANK', 'APOLLOTYRE', 'ARVIND', 'ASHOKLEY', 'ASIANPAINT', 'AUROPHARMA', 'AXISBANK', 'BANKBARODA', 'BANKINDIA', 'BATAINDIA', 'BHARATFORG', 'BHARTIARTL', 'BIOCON', 'CANBK', 'CENTRALBK', 'CENTURYTEX', 'CESC', 'CHAMBLFERT', 'CIPLA', 'COALINDIA', 'COLPAL', 'DABUR', 'DLF', 'DRREDDY', 'EXIDEIND', 'FEDERALBNK', 'GAIL', 'GMRINFRA', 'GODREJIND', 'GRASIM', 'GSPL', 'HAVELLS', 'HCLTECH', 'HDFC', 'HDFCBANK', 'HDIL', 'HEROMOTOCO', 'HEXAWARE', 'HINDALCO', 'HINDPETRO', 'HINDUNILVR', 'HINDZINC', 'IBREALEST', 'ICICIBANK', 'IDBI', 'IDEA', 'IDFC', 'IFCI', 'IGL', 'INDHOTEL', 'INDIACEM', 'INDUSINDBK', 'INFY', 'IOB', 'IOC', 'IRB', 'ITC', 'JINDALSTEL', 'JISLJALEQS', 'JPASSOCIAT', 'JPPOWER', 'JSWENERGY', 'JSWSTEEL', 'JUBLFOOD', 'KOTAKBANK', 'KTKBANK', 'LICHSGFIN', 'LT', 'LUPIN', 'M&M', 'MARUTI', 'MCDOWELL-N', 'MRF', 'NCC', 'NMDC', 'NTPC', 'OFSS', 'ONGC', 'OPTOCIRCUI', 'ORIENTBANK', 'PNB', 'POWERGRID', 'PTC', 'PUNJLLOYD', 'RAYMOND', 'RCOM', 'RECLTD', 'RELCAPITAL', 'RELIANCE', 'RELINFRA', 'RENUKA', 'SBIN', 'SCI', 'SINTEX', 'SOUTHBANK', 'SRTRANSFIN', 'SUNPHARMA', 'SUNTV', 'SUZLON', 'SYNDIBANK', 'TATACHEM', 'TATACOMM', 'TATAGLOBAL', 'TATAMOTORS', 'TATAMTRDVR', 'TATAPOWER', 'TATASTEEL', 'TCS', 'TECHM', 'TITAN', 'UCOBANK', 'ULTRACEMCO', 'UNIONBANK', 'UNITECH', 'VOLTAS', 'WELCORP', 'WIPRO', 'YESBANK', 'BHEL', 'BPCL', 'DISHTV', 'DIVISLAB', 'GVKPIL', 'NHPC', 'MPHASIS', 'SIEMENS', 'PEL', 'PETRONET', 'PFC', 'RPOWER', 'SAIL', 'ZEEL']
        break
while 1:
    kwss=int(input("enter timeframe 1/2/3/5"))
    if kwss:
        time_frame_bktst      =kwss
        spl=time_frame_bktst-1
        back_test_timeframe=spl
        break

while 1:
    d_d=int(input("enter days of backtesting"))
    if d_d:
        zap=kite.historical_data(3677697,"2019-05-10","2020-08-16" ,"day",0)
        zapp=pd.DataFrame(zap).tail(d_d)
        s_date=zapp.iloc[1,1]
        kk=str(s_date)
        gg=kk[:10]
        sdate_backtest=str(gg.strip())
        e_date=zapp.iloc[-1,1]
        kk=str(e_date)
        gg=kk[:10]
        todate_backtest =str(gg.strip())
        print(sdate_backtest)
        print(todate_backtest)
        break

while 1:
    quu=int(input("enter amount ???"))
    if quu:
        eexchange="NSE"
        productt="MIS"
        qu=int(quu)
        break

        
# ignore warnings
def fxn():
    warnings.warn("deprecated", DeprecationWarning)

with warnings.catch_warnings():
    warnings.simplefilter("ignore")
    fxn()
warnings.filterwarnings("ignore")

print("SCANNING START")

# margins on stock 

marg=[3.0, 3.0, 3.0, 3.0, 12.5, 3.0, 5.0, 5.0, 5.0, 3.0, 3.0, 3.0, 11.0, 3.0, 3.0, 12.5, 12.5, 3.0, 5.0, 12.5, 5.0, 3.0, 12.5, 12.5, 3.0, 3.0, 3.0, 3.0, 12.5, 3.0, 3.0, 12.5, 12.5, 3.0, 12.5, 3.0, 12.5, 12.5, 3.0, 3.0, 12.5, 10.0, 5.0, 12.5, 3.0, 12.5, 3.0, 12.5, 3.0, 3.0, 12.5, 5.0, 5.0, 12.5, 3.0, 3.0, 12.5, 12.5, 12.5, 3.0, 12.5, 12.5, 3.0, 3.0, 12.5, 3.0, 3.0, 3.0, 3.0, 12.5, 3.0, 12.5, 3.0, 3.0, 12.5, 12.5, 12.5, 3.0, 3.0, 12.5, 12.5, 3.0, 3.0, 3.0, 3.0, 12.5, 3.0, 12.5, 3.0, 3.0, 3.0, 3.0, 3.0, 3.0, 3.0, 5.0, 8.3, 3.0, 8.3, 3.0, 3.0, 5.0, 3.0, 12.5, 3.0, 3.0, 3.0, 3.0, 3.0, 12.5, 5.6, 3.0, 12.5, 12.5, 12.5, 3.0, 3.0, 3.0, 3.0, 5.0, 3.0, 3.0, 3.0, 3.0, 3.0, 3.0, 3.0, 3.0, 3.0, 12.5, 3.0, 3.0, 5.0, 3.0, 3.0, 12.5, 3.0, 3.0, 10.0, 3.0, 3.0, 12.5, 3.0, 3.0, 3.0, 3.0, 3.0, 3.0, 3.0, 12.5, 3.0, 3.0, 12.5, 12.5, 3.0, 12.5, 3.0, 3.0, 12.5, 12.5, 3.0, 3.0, 12.5, 3.0, 9.0, 12.5, 12.5, 3.0, 3.0, 3.0, 3.0, 3.0, 12.5, 3.0, 3.0, 9.0, 12.5, 5.0, 3.0, 12.5, 3.0, 3.0, 12.5, 3.0, 3.0, 3.0, 10.0, 12.5, 3.0, 12.5, 12.5, 3.0, 3.0, 3.0, 3.0, 8.3, 3.0, 3.0, 12.5, 3.0, 3.0, 3.0, 3.0, 11.0, 3.0, 3.0, 3.0, 3.0, 3.0, 3.0, 3.0, 12.5, 3.0, 5.0, 10.0, 3.0, 12.5, 3.0, 3.0, 3.0, 3.0, 3.0, 3.0, 3.0, 12.5, 3.0, 5.0, 3.0, 3.0, 11.0, 3.0, 3.0, 12.5, 3.0, 10.0, 12.5, 12.5, 12.5, 12.5, 3.0, 3.0, 3.0, 3.0, 3.0, 3.0, 12.5, 3.0, 3.0, 3.0, 12.5, 3.0, 12.5, 3.0, 3.0, 12.5, 12.5, 3.0, 12.5, 12.5, 3.0, 3.0, 3.0, 12.5, 3.0, 3.0, 3.0, 5.0, 3.0, 12.5, 3.0, 3.0, 3.0, 12.5, 3.0, 12.5, 3.0, 3.0, 3.0, 12.5, 12.5, 12.5, 3.0, 3.0, 3.0, 3.0, 3.0, 10.0, 12.5, 3.0, 12.5, 3.0, 3.0, 12.5, 3.0, 12.5, 12.5, 3.0, 12.5, 3.0, 3.0, 5.0, 3.0, 3.0, 3.0, 3.0, 12.5, 3.0, 12.5, 11.0, 3.0, 3.0, 3.0, 3.0, 12.5, 3.0, 12.5, 3.0, 3.0, 3.0, 12.5, 3.0, 3.0, 3.0, 3.0, 12.5, 3.0, 3.0, 3.0, 3.0, 3.0, 12.5, 3.0, 12.5, 12.5, 3.0, 12.5, 3.0, 3.0, 12.5, 3.0, 3.0, 3.0, 3.0, 3.0, 12.5, 3.0, 3.0, 3.0, 3.0, 3.0, 3.0, 3.0, 12.5, 3.0, 3.0, 3.0, 3.0, 3.0, 3.0, 12.5, 3.0, 12.5, 3.0, 3.0, 3.0, 3.0, 3.0, 3.0, 3.0, 3.0, 3.0, 5.0, 11.0, 10.0, 3.0, 3.0, 3.0, 3.0, 5.0, 3.0, 11.0, 3.0, 3.0, 3.0, 3.0, 3.0, 12.5, 3.0, 3.0, 12.5, 12.5, 3.0, 9.0, 9.0, 12.5, 3.0, 12.5, 3.0, 12.5, 12.5, 3.0, 3.0, 3.0, 3.0, 3.0, 3.0, 3.0, 12.5, 3.0, 3.0, 12.5, 12.5, 3.0, 3.0, 3.0, 3.0, 3.0, 3.0, 12.5, 3.0, 12.5, 3.0, 9.0, 12.5, 11.0, 3.0, 12.5, 3.0, 5.0, 3.0, 3.0, 3.0, 12.5, 3.0, 3.0, 3.0, 3.0, 3.0, 3.0, 3.0, 3.0, 12.5, 3.0, 3.0, 5.0]
symb=['3MINDIA', 'AARTIIND','ABB','ABFRL', 'ACC', 'ACE', 'ADANIENT', 'ADANIPORTS', 'ADANIPOWER', 'AIAENG', 'AJANTPHARM', 'AKZOINDIA', 'ALBK', 'ALKEM', 'ALLCARGO', 'AMARAJABAT', 'AMBUJACEM', 'ANANTRAJ', 'APOLLOHOSP', 'APOLLOTYRE', 'ARVIND', 'ASAHIINDIA', 'ASHOKLEY', 'ASIANPAINT', 'ASTRAZEN', 'ATFL', 'ATUL', 'AUBANK', 'AUROPHARMA', 'AUTOAXLES', 'AVANTIFEED', 'AXISBANK', 'BAJAJ-AUTO', 'BAJAJELEC', 'BAJAJFINSV', 'BAJAJHLDNG', 'BAJFINANCE', 'BALKRISIND', 'BALRAMCHIN', 'BANCOINDIA', 'BANKBARODA', 'BANKBEES', 'BANKINDIA', 'BATAINDIA', 'BBTC', 'BEL', 'BEML', 'BERGEPAINT', 'BFUTILITIE', 'BHARATFIN', 'BHARATFORG', 'BHARTIARTL', 'BHEL', 'BIOCON', 'BLKASHYAP', 'BLUEDART', 'BOSCHLTD', 'BPCL', 'BRITANNIA', 'BSE', 'CADILAHC', 'CANBK', 'CANFINHOME', 'CAPACITE', 'CASTROLIND', 'CDSL', 'CEATLTD', 'CENTRUM', 'CENTURYPLY', 'CENTURYTEX', 'CEREBRAINT', 'CESC', 'CGCL', 'CHENNPETRO', 'CHOLAFIN', 'CIPLA', 'COALINDIA', 'COCHINSHIP', 'COFFEEDAY', 'COLPAL', 'CONCOR', 'COROMANDEL', 'CRISIL', 'CROMPTON', 'CUB', 'CUMMINSIND', 'CYIENT', 'DABUR', 'DALMIASUG', 'DBCORP', 'DCBBANK', 'DEN', 'DHAMPURSUG', 'DHFL', 'DIAMONDYD', 'DISHTV', 'DIVISLAB', 'DIXON', 'DLF', 'DMART', 'DREDGECORP', 'DRREDDY', 'ECLERX', 'EICHERMOT', 'EIDPARRY', 'EIHOTEL', 'ELECTCAST', 'EMAMILTD', 'ENDURANCE', 'ENGINERSIN', 'EQUITAS', 'ERIS', 'ESCORTS', 'EXIDEIND', 'FEDERALBNK', 'FEL', 'FINCABLES', 'FORTIS', 'FRETAIL', 'GAIL', 'GDL', 'GEPIL', 'GESHIP', 'GET&D', 'GHCL', 'GICHSGFIN', 'GICRE', 'GILLETTE', 'GLAXO', 'GLENMARK', 'GLOBUSSPR', 'GMBREW', 'GMRINFRA', 'GNFC', 'GODREJAGRO', 'GODREJCP', 'GODREJIND', 'GODREJPROP', 'GOLDBEES', 'GPPL', 'GRANULES', 'GRASIM', 'GREAVESCOT', 'GSFC', 'GSKCONS', 'GSPL', 'GUJALKALI', 'GUJFLUORO', 'GUJGASLTD', 'HAVELLS', 'HBLPOWER', 'HCL-INSYS', 'HCLTECH', 'HDFC', 'HDFCAMC', 'HDFCBANK', 'HDFCLIFE', 'HEIDELBERG', 'HEROMOTOCO', 'HEXAWARE', 'HGS', 'HIKAL', 'HINDALCO', 'HINDCOPPER', 'HINDPETRO', 'HINDUNILVR', 'HINDZINC', 'HONAUT', 'HSCL', 'HSIL', 'HUDCO', 'IBULHSGFIN', 'ICICIBANK', 'ICICIGI', 'ICICINIFTY', 'ICICIPRULI', 'IDBI', 'IDEA', 'IDFC', 'IDFCFIRSTB', 'IEX', 'IFCI', 'IGL', 'INDHOTEL', 'INDIACEM', 'INDIANB', 'INDIGO', 'INDUSINDBK', 'INFIBEAM', 'INFRATEL', 'INFY', 'INOXLEISUR', 'INOXWIND', 'INTELLECT', 'IOB', 'IOC', 'IPCALAB', 'IRB', 'ITC', 'ITDCEM', 'JAICORPLTD', 'JAMNAAUTO', 'JAYSREETEA', 'JINDALSTEL', 'JINDWORLD', 'JKCEMENT', 'JKPAPER', 'JKTYRE', 'JMFINANCIL', 'JSLHISAR', 'JSWENERGY', 'JSWSTEEL', 'JUBILANT', 'JUBLFOOD', 'JUSTDIAL', 'JYOTHYLAB', 'KAJARIACER', 'KALPATPOWR', 'KANSAINER', 'KARURVYSYA', 'KEC', 'KEI', 'KIRIINDUS', 'KOTAKBANK', 'KOTAKNIFTY', 'BSOFT', 'KSCL', 'KTKBANK', 'L&TFH', 'LALPATHLAB', 'LIBERTSHOE', 'LICHSGFIN', 'LINCOLN', 'LIQUIDBEES', 'LT', 'LUPIN', 'M&M', 'M&MFIN', 'M50', 'MAHINDCIE', 'MAHLOG', 'MAHSEAMLES', 'MAJESCO', 'MANALIPETC', 'MANAPPURAM', 'MANGTIMBER', 'MANINDS', 'MANINFRA', 'MARICO', 'MARKSANS', 'MARUTI', 'MASFIN', 'MASTEK', 'MCDOWELL-N', 'MCX', 'MEGH', 'MFSL', 'MGL', 'MIDHANI', 'MINDACORP', 'MINDAIND', 'MINDTREE', 'MMTC', 'MOIL', 'MOLDTKPAC', 'MOTHERSUMI', 'MPHASIS', 'MRF', 'MRPL', 'MUKANDLTD', 'MUNJALAU', 'MUTHOOTFIN', 'NATCOPHARM', 'NATIONALUM', 'NAUKRI', 'NAVINFLUOR', 'NAVNETEDUL', 'NBCC', 'NCC', 'NESTLEIND', 'NETWORK18', 'NFL', 'NH', 'NHPC', 'NIACL', 'NIFTYBEES', 'NIITTECH', 'NLCINDIA', 'NMDC', 'NOCIL', 'NRBBEARING', 'NTPC', 'OBEROIRLTY', 'OFSS', 'OIL', 'OMAXE', 'ONGC', 'ORIENTBANK', 'ORIENTCEM', 'PAGEIND', 'PAPERPROD', 'PARAGMILK', 'PATELENG', 'PCJEWELLER', 'PEL', 'PERSISTENT', 'PETRONET', 'PFC', 'PFIZER', 'PGHH', 'PHILIPCARB', 'PHOENIXLTD', 'PIDILITIND', 'PIIND', 'PNB', 'PNBGILTS', 'PNBHOUSING', 'POLYPLEX', 'POWERGRID', 'PRAJIND', 'PRESTIGE', 'PTC', 'PURVA', 'PVR', 'QUICKHEAL', 'RADICO', 'RADIOCITY', 'RAJESHEXPO', 'RALLIS', 'RAMCOCEM', 'RAMCOIND', 'RAYMOND', 'RBLBANK', 'RCF', 'RECLTD', 'RELAXO', 'RELCAPITAL', 'RELIANCE', 'RELINFRA', 'REPCOHOME', 'RICOAUTO', 'RIIL', 'RKFORGE', 'SAIL', 'SALZERELEC', 'SANGHIIND', 'SANGHVIMOV', 'SANOFI', 'SAREGAMA', 'SATIN', 'SBILIFE', 'SBIN', 'SCHAEFFLER', 'SCHNEIDER', 'SCI', 'SELAN', 'SEQUENT', 'SHARDAMOTR', 'SHREECEM', 'SHRIRAMCIT', 'SIEMENS', 'SIMPLEXINF', 'SIS', 'SJVN', 'SKFINDIA', 'SNOWMAN', 'SOBHA', 'SOLARINDS', 'SOUTHBANK', 'SPARC', 'SRF', 'SRTRANSFIN', 'STAR', 'STCINDIA', 'STRTECH', 'SUNDARMFIN', 'SUNDRMFAST', 'SUNPHARMA', 'SUNTECK', 'SUNTV', 'SUPREMEIND', 'SUVEN', 'SYNDIBANK', 'SYNGENE', 'TAKE', 'TATACHEM', 'TATACOFFEE', 'TATACOMM', 'TATAELXSI', 'TATAGLOBAL', 'TATAINVEST', 'TATAMOTORS', 'TATAMTRDVR', 'TATAPOWER', 'TATASPONGE', 'TATASTEEL', 'TCI', 'TCS', 'TECHM', 'TEXRAIL', 'THERMAX', 'THOMASCOOK', 'THYROCARE', 'TIFIN', 'TIMETECHNO', 'TINPLATE', 'TITAN', 'TNPETRO', 'TNPL', 'TORNTPHARM', 'TORNTPOWER', 'TRENT', 'TRIDENT', 'TRIGYN', 'TRIVENI', 'TTKPRESTIG', 'TV18BRDCST', 'TVSMOTOR', 'TWL', 'UBL', 'UCOBANK', 'UJJIVAN', 'ULTRACEMCO', 'UNIONBANK', 'UNIVCABLES', 'UPL', 'USHAMART', 'VEDL', 'VGUARD', 'VIJAYABANK', 'VIPIND', 'VOLTAS', 'VTL', 'WABCOINDIA', 'WALCHANNAG', 'WELCORP', 'WELENT', 'WELSPUNIND', 'WHIRLPOOL', 'WINDMACHIN', 'WIPRO', 'WOCKPHARMA', 'WONDERLA', 'YESBANK', 'ZEEL']
dr={"margin":marg, "symbls":symb} 
check_list=pd.DataFrame(dr)

# code for rounding

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

# converting candle timeframe 

def time_con(time,df):
    z = 0
    chg = []
    chg_index = 0
    timeframe = time
    date = np.array([])
    for i in range(len(df)):
        date = np.hstack((date,str(df.loc[i,"date"])))
    open_np = df.open.values
    high_np = df.high.values
    low_np = df.low.values
    close_np = df.close.values
#     volume_np = df.volume.values
#     print(date)
    for j in range(len(date)):
        if date[j][11:16] == "09:15":
            chg.append(j)
    last = len(df)-1
    timeframe_value = int(date[last][11:13])*60 + int(date[last][14:16]) - (9*60+15)
    #print(timeframe_value)
    if timeframe_value%timeframe==0:
        chg.append(len(df)-1)
    else:
        chg.append(len(df)-timeframe)
    np_date=np.array([])
    np_open = np.array([])
    np_high = np.array([])
    np_low = np.array([])
    np_close = np.array([])
#     np_volume = np.array([])
    for i in range(len(date)-timeframe):
        if i>=z:
            chg_index+=1
            if (chg_index < len(chg)):
                for k in range(i,chg[chg_index],timeframe):
#                     print(date[k])
#                     print(k,k+timeframe)
                    try:
                        np_close = np.hstack((np_close,close_np[k+timeframe-1]))
                    except:
                        break
                    np_date = np.hstack((np_date,date[k]))
                    np_open = np.hstack((np_open,open_np[k]))
                    np_high = np.hstack((np_high,np.amax(high_np[k:k+timeframe])))
#                     print(high_np[k:k+timeframe])
                    np_low = np.hstack((np_low,np.amin(low_np[k:k+timeframe])))
#                     print(low_np[k:k+timeframe])
                    
#                     np_volume = np.hstack((np_volume,np.sum(volume_np[k:k+timeframe])))
                    z = i+timeframe
                    z=chg[chg_index]
    else:
        con_df = pd.DataFrame({"date":np_date,"open":np_open,"high":np_high,"low":np_low,"close":np_close})
        return con_df
    ##

aa=0
print("  \t \t \t \n Getting All tokens for processing BUY SELL ")
ks=strftime("%a, %d %b %Y %I:%M:%S %p")
print(" Now checking Condition of BUY sell of GUPPY ")
display(strftime("%a, %d %b %Y %I:%M:%S %p"))
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=[]

##################
#new
fail_buy_backtest=[]
fail_sell_backtest=[]
buy_bid_new=[]
sell_bid_new=[]
red_new=[]
green_new=[]
ignores_sell=[]
ignores_buy=[]

#######

def ashi():
    global a
    global tokenall
    global BUY_listindicator
    global SELL_listindicator
    ak=1
    while (True):
        #display(strftime("%a, %d %b %Y %I:%M:%S %p"))
        dff=kite.historical_data(tokenall[a],sdate,todate,"minute",0)
        dff=pd.DataFrame(dff)
        avv=dff[['date','open','high','low','close']]
        av = time_con(time_frame_bktst,avv)    ## candel conversion
        print(time_frame_bktst)
        kk=str(av.iloc[-1,1]).split("+")
        #print(av.iloc[-1,1])
        
        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:
            df=av[:-1]
        else:
            df=av
        #df=pd.DataFrame(dfw[['date','open','high','low','close']])
        #break
        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(" \t \t \t \t ZERODHA ADVANCE BOT ")
        #display(strftime("%a, %d %b %Y %I:%M:%S %p"))
        print("Current candel checking  no       " , a)
        print("Current Colour on this token is   " , gup.iloc[-1,5])
        print("Current Symbol                    " , ss[a])
        print("Data fetched ! compressing Data for indicator ...")
      
        
        if "green" in gup.iloc[-1,5]:
            print("BUY stock found ")
            ttradingsymbol=ss[a]
            ttoken=tokenall[a]
            #
            # checking already placed or not if placed then ignore else place order on this stock
            #
              
            
            kl=kite.orders()
            if kl:
                kk=list((pd.DataFrame(kite.orders())[["instrument_token"]])["instrument_token"])
                if ttoken in kk:
                    print(" ALREADY USED !! ")
                    print(" Token   is :=        ", ttoken)
                    print(" Trading Symbol is := ", ttradingsymbol)
                    print(" SORRY !! This order already exists \n so not going to place this order !! ")
                    ignores_buy.append(ttradingsymbol)
                else:
                    # backtesting result
                    
                    print(" fresh order now checking backtesting")
                    print("\n Data fetched  ! compressing Data for backtesting ...")
                    strike_rate = 0
                    strike_rate_list = []
                    timeframe = []
                    timeframe_list = []
                    pnl = 0
                    pnl_list = []
                    for t in range(1,7):
                        dfw=kite.historical_data(ttoken,sdate_backtest,todate_backtest,"minute",0)
                        df=pd.DataFrame(dfw)
                        df=pd.DataFrame(df[['date','open','high','low','close']])
                        df = time_con(time_frame_bktst,df)
                        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)
                        df['bid_value'] = 0
                        df['executed_value'] = 0
                        df['diff'] = 0
                        df['pnl'] = 0
                        qty = int ( qu/ (gup.iloc[-1,2]) )
                        var = False
                        var_2 = False
                        var_1 = False
                        #****************************
                        for i in range(len(df)):
                            zz=df.loc[i,"date"]
                            za=str(zz)[11:13]
                            if za=="15":
                                if var==True and var1==True:
                                    df.loc[i,'diff'] =  bid_value - df.loc[i,'close']
                                    df.loc[i,'pnl'] = ( bid_value /bid_value)*df.loc[i,'diff']
                                    ##
                                    var=False
                                    var1=False
                                if var==True and var1==False:
                                    var=False
                                var_2=True
                            if za!="15":
                                var_2=False
                            if var==False and var_2==False:
                                if df.loc[i,'arrow_color']=='green':
                                    bid_value = (df.loc[i,'high']+df.loc[i,'ATR']*.25)+(df.loc[i,'ATR']*.1)
                                    df.loc[i,'bid_value'] =bid_value
                                    var=True
                                    var1=False
                            if var==True and var1==False and var_2==False:
                                if df.loc[i,'high'] > bid_value and df.loc[i,'low'] < bid_value:
                                    df.loc[i,'executed_value']=bid_value
                                    var1=True
                            if var==True and var1==True and var_2==False:
                                if df.loc[i,'arrow_color']=='red':
                                    df.loc[i,'diff'] =  df.loc[i,'close'] - bid_value
                                    df.loc[i,'pnl'] = ( bid_value /bid_value)*df.loc[i,'diff']
                                    var=False
                                    var1=False
                        #****************************
                        list_1 = df['pnl']
                        pos_count = len(list(filter(lambda x: (x>0),list_1)))
                        neg_count = len(list(filter(lambda x: (x<0),list_1)))
                        total_trade = pos_count + neg_count
                        try :
                            strike_rate = pos_count/total_trade
                        except:
                            strike_rate = 0
                        pnl = df['pnl'].sum()
                        pnl_list.append(pnl)
                        timeframe_list.append(t)
                        strike_rate_list.append(strike_rate)
                    main_df = pd.DataFrame({'timeframe':timeframe_list,'pnl':pnl_list,'strike_rate':strike_rate_list})
                    s=f"{ttradingsymbol}.csv"
                    #df.to_csv(s)
                    main_df.to_csv(s)
                    print("complete")                
                    #file
                    st=ttradingsymbol+"_pnl_sheet"
                    s=f"{st}.csv"
                    df.to_csv(s)
                    ##############
                    pnl_rate=main_df.loc[back_test_timeframe,'pnl'] #10 
                    stk_rate=main_df.loc[back_test_timeframe,'strike_rate']  #.5 
                    print("PnL        :=",pnl_rate)
                    print("strike rate:=",stk_rate )
                    if pnl_rate >= 10 and stk_rate >= 0.55:
                        print("passed in backtesting pnL is ")
                        print("TRUE !! so going to place order of ",ttradingsymbol)
                        try:
                            # finding quantity
                            max_trade=5
                            psf=qu/max_trade
                            check_list_found=(check_list[check_list["symbls"].str.contains(ttradingsymbol)==True])[["margin","symbls"]]
                            fund_margin=float(check_list_found.iloc[-1,0])
                            amount_total = psf*fund_margin
                            kk=int ( amount_total/ (avv.iloc[-1,2]) ) 
                            print("total stock :=", kk)
                            if kk>=1:
                                xa=float(avv.iloc[-1,2]+(avv.iloc[-1,6]*.25))
                                cur_high=avg_ha(xa)
                                xb=cur_high+float(avv.iloc[-1,6])*0.1
                                lim_price=avg_ha(xb)
                                print("\n")
                                display(avv.tail(1))
                                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.ltp(ttoken)) 
                                #kite_drop=1000000001
                                kite.place_order(variety="regular",tradingsymbol=ttradingsymbol,quantity=kk,exchange=eexchange,order_type='SL',price=lim_price ,trigger_price=cur_high,transaction_type='BUY',product=productt,tag="advgu")
                                print("buy order id is                                               ",kite_drop)
                                display(strftime("%a, %d %b %Y %I:%M:%S %p"))
                                print("\n")
                                buy_bid_new.append(ttradingsymbol)
                            else:
                                print("quantity error")
                                pass
                        except:
                            # order 
                            
                            print("Error in Trigger_price and Price !! ")
                            ltpp=pd.DataFrame(kite.ltp(ttoken)).iloc[-1,0]
                            cur_high=avg_ha(ltpp)
                            xb=cur_high+float(gup.iloc[-1,6])*0.25
                            lim_price=avg_ha(xb)
                            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.ltp(ttoken)) 
                            #kite_drop=1000000001
                            kite.place_order(variety="regular",tradingsymbol=ttradingsymbol,quantity=kk,exchange=eexchange,order_type='SL',price=lim_price ,trigger_price=cur_high,transaction_type='BUY',product=productt,tag="advgu")
                            print("buy order id is                                               ",kite_drop)
                            display(strftime("%a, %d %b %Y %I:%M:%S %p"))
                            print("\n")
                            buy_bid_new.append(ttradingsymbol)
                            pass
                    else:
                        print("fail in backtestig")
                        fail_buy_backtest.append(ttradingsymbol)
                        pass
                    
                    
                    ##################################
                    
        if "red" in gup.iloc[-1,5]:
            print("SELL stock found")
            ttradingsymbol=ss[a]
            ttoken=tokenall[a]
            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 := ", ttradingsymbol)
                    print(" SORRY !! This order already exists \n so not going to place this order !! ")
                    ignores_sell.append(ttradingsymbol)
                else:
                    print("checking backtesting")
                    print("\n Data fetched  ! compressing Data for backtesting ...")
                    ########################
                    strike_rate = 0
                    strike_rate_list = []
                    timeframe = []
                    timeframe_list = []
                    pnl = 0
                    pnl_list = []

                    for t in range(1,7):
                        dfw=kite.historical_data(ttoken,sdate_backtest,todate_backtest,"minute",0)
                        dfw=pd.DataFrame(dfw)
                        df=pd.DataFrame(dfw[['date','open','high','low','close']])
                        df= time_con(time_frame_bktst,df)
                        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)
                        df['bid_value'] = 0
                        df['executed_value'] = 0
                        df['diff'] = 0
                        df['pnl'] = 0
                        qty = int ( qu/ (gup.iloc[-1,2]) )
                        var = False
                        var_2 = False
                        var_1 = False
                        #*************************
                        for i in range(len(df)):
                            zz=df.loc[i,"date"]
                            za=str(zz)[11:13]
                            if za=="15":
                                if var==True and var1==True:
                                    df.loc[i,'diff'] =  bid_value - df.loc[i,'close']
                                    df.loc[i,'pnl'] = ( bid_value /bid_value)*df.loc[i,'diff']
                                    ##
                                    var=False
                                    var1=False
                                if var==True and var1==False:
                                    var=False
                                var_2=True
                            if za!="15":
                                var_2=False
                            if var==False and var_2==False:
                                if df.loc[i,'arrow_color']=='red':
                                    bid_value = (df.loc[i,'low']-df.loc[i,'ATR']*.25)-(df.loc[i,'ATR']*.1)
                                    df.loc[i,'bid_value'] =bid_value
                                    var=True
                                    var1=False
                            if var==True and var1==False and var_2==False:
                                if df.loc[i,'high'] > bid_value and df.loc[i,'low'] < bid_value:
                                    df.loc[i,'executed_value']=bid_value
                                    var1=True
                            if var==True and var1==True and var_2==False:
                                if df.loc[i,'arrow_color']=='green':
                                    df.loc[i,'diff'] =  bid_value - df.loc[i,'close'] 
                                    df.loc[i,'pnl'] = ( bid_value /bid_value)*df.loc[i,'diff']
                                    var=False
                                    var1=False
                        #***********************
                        list_1 = df['pnl']
                        pos_count = len(list(filter(lambda x: (x>0),list_1)))
                        neg_count = len(list(filter(lambda x: (x<0),list_1)))
                        total_trade = pos_count + neg_count
                        try :
                            strike_rate = pos_count/total_trade
                        except:
                            strike_rate = 0
                        #print(strike_rate)
                        pnl = df['pnl'].sum()
                        pnl_list.append(pnl)
                        timeframe_list.append(t)
                        strike_rate_list.append(strike_rate)
                    main_df = pd.DataFrame({'timeframe':timeframe_list,'pnl':pnl_list,'strike_rate':strike_rate_list})
                    s=f"{ttradingsymbol}.csv"
                    main_df.to_csv(s)
                    #file
                    st=ttradingsymbol+"_pnl_sheet"
                    s=f"{st}.csv"
                    df.to_csv(s)
                    print("complete")
                    pnl_rate=main_df.loc[back_test_timeframe,'pnl'] #10 
                    stk_rate=main_df.loc[back_test_timeframe,'strike_rate']  #.5 
                    print("PnL         :=",pnl_rate)
                    print("strike rate :=",stk_rate )
                    if pnl_rate >= 10 and stk_rate >= 0.55:
                        print("pass in backtest")
                        print("TRUE !! so going to place order of ", ttradingsymbol) 
                        try:
                            ##
                            # finding quantity
                            
                            max_trade=5
                            psf=qu/max_trade
                            check_list_found=(check_list[check_list["symbls"].str.contains(ttradingsymbol)==True])[["margin","symbls"]]
                            fund_margin=float(check_list_found.iloc[-1,0])
                            amount_total = psf*fund_margin
                            kk=int ( amount_total/ (avv.iloc[-1,2]) ) 
                            print("total stock :=", kk)
                            
                            ##
                            if kk>=1:
                                xa=float(avv.iloc[-1,3]-avv.iloc[-1,6]*.25)
                                price_sell=avg_ha(xa) # TRIGER PRICE (LARGE)
                                xb=price_sell-float(avv.iloc[-1,6])*0.1
                                triger_sell=avg_ha(xb) #PRICE (SMALL)
                                print("\n")
                                display(avv.tail(1))
                                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.ltp(ttoken))
                                #kite_drop=111111
                                kite_drop=kite.place_order(order_type='SL',price= triger_sell,trigger_price=price_sell,variety="regular",tradingsymbol=ttradingsymbol,quantity=kk,exchange=eexchange,transaction_type='SELL',product=productt,tag="advgu")
                                print("SELL order id is                                                ",kite_drop)
                                display(strftime("%a, %d %b %Y %I:%M:%S %p"))
                                print("\n")
                                sell_bid_new.append(ttradingsymbol) 
                            else:
                                print("error in order quantity low")
                                pass
                        except:
                            print("Error in Prices and Triger_price ")                   
                            ltpp=pd.DataFrame(kite.ltp(ttoken)).iloc[-1,0]
                            price_sell=avg_ha(ltpp) # TRIGER PRICE (LARGE)
                            xb=price_sell-float(gup.iloc[-1,6])*0.25
                            triger_sell=avg_ha(xb) #PRICE (SMALL)
                            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.ltp(ttoken))
                            #kite_drop=111111
                            kite_drop=kite.place_order(order_type='SL',price= triger_sell,trigger_price=price_sell,variety="regular",tradingsymbol=ttradingsymbol,quantity=kk,exchange=eexchange,transaction_type='SELL',product=productt,tag="advgu")
                            print("SELL order id is                                                ",kite_drop)
                            display(strftime("%a, %d %b %Y %I:%M:%S %p"))
                            print("\n")
                            sell_bid_new.append(ttradingsymbol)
                            pass
                    else:
                        print("fail in backtesting")
                        fail_sell_backtest.append(ttradingsymbol)
                        
        a=a+1
        if a==len(tokenall):
            print(" SCAN COMPLETED !!")
            display(ks)
            display(strftime("%a, %d %b %Y %I:%M:%S %p"))
            print("BUY bid placed                     =", buy_bid_new)
            print("Sell bid placed                    =", sell_bid_new)
            print("\n")
            print("BUY fail in backtesting            =", fail_buy_backtest)
            print("SELL fail in backtesting           =", fail_sell_backtest)
            print("\n")
            print("BUY token ignored 'already placed' =", ignores_buy)
            print("SELL token ignored 'already placed'=", ignores_sell)
            print("\n")
            print("Code Completed ")
            
            a=0
            break
            
ashi()
				
			

Output – 

				
					nifty or fno ?nifty
enter timeframe 1/2/3/55
enter days of backtesting7
2019-08-23
2019-08-30
enter amount ???500000
SCANNING START
  	 	 	 
 Getting All tokens for processing BUY SELL 
 Now checking Condition of BUY sell of GUPPY 
'Sun, 01 Sep 2019 12:51:14 AM'
5


 	 	 	 	 ZERODHA ADVANCE BOT 
Current candel checking  no        0
Current Colour on this token is    none
Current Symbol                     ADANIPORTS
Data fetched ! compressing Data for indicator ...
5


 	 	 	 	 ZERODHA ADVANCE BOT 
Current candel checking  no        1
Current Colour on this token is    none
Current Symbol                     ASIANPAINT
Data fetched ! compressing Data for indicator ...
5


 	 	 	 	 ZERODHA ADVANCE BOT 
Current candel checking  no        2
Current Colour on this token is    none
Current Symbol                     AXISBANK
Data fetched ! compressing Data for indicator ...
5


 	 	 	 	 ZERODHA ADVANCE BOT 
Current candel checking  no        3
Current Colour on this token is    none
Current Symbol                     BAJAJ-AUTO
Data fetched ! compressing Data for indicator ...
5


 	 	 	 	 ZERODHA ADVANCE BOT 
Current candel checking  no        4
Current Colour on this token is    none
Current Symbol                     BAJFINANCE
Data fetched ! compressing Data for indicator ...
5


 	 	 	 	 ZERODHA ADVANCE BOT 
Current candel checking  no        5
Current Colour on this token is    none
Current Symbol                     BAJAJFINSV
Data fetched ! compressing Data for indicator ...
5


 	 	 	 	 ZERODHA ADVANCE BOT 
Current candel checking  no        6
Current Colour on this token is    none
Current Symbol                     BPCL
Data fetched ! compressing Data for indicator ...
5


 	 	 	 	 ZERODHA ADVANCE BOT 
Current candel checking  no        7
Current Colour on this token is    none
Current Symbol                     BHARTIARTL
Data fetched ! compressing Data for indicator ...
5


 	 	 	 	 ZERODHA ADVANCE BOT 
Current candel checking  no        8
Current Colour on this token is    none
Current Symbol                     INFRATEL
Data fetched ! compressing Data for indicator ...
5


 	 	 	 	 ZERODHA ADVANCE BOT 
Current candel checking  no        9
Current Colour on this token is    none
Current Symbol                     BRITANNIA
Data fetched ! compressing Data for indicator ...
5


 	 	 	 	 ZERODHA ADVANCE BOT 
Current candel checking  no        10
Current Colour on this token is    none
Current Symbol                     CIPLA
Data fetched ! compressing Data for indicator ...
5


 	 	 	 	 ZERODHA ADVANCE BOT 
Current candel checking  no        11
Current Colour on this token is    none
Current Symbol                     COALINDIA
Data fetched ! compressing Data for indicator ...
5


 	 	 	 	 ZERODHA ADVANCE BOT 
Current candel checking  no        12
Current Colour on this token is    none
Current Symbol                     DRREDDY
Data fetched ! compressing Data for indicator ...
5


 	 	 	 	 ZERODHA ADVANCE BOT 
Current candel checking  no        13
Current Colour on this token is    none
Current Symbol                     EICHERMOT
Data fetched ! compressing Data for indicator ...
5


 	 	 	 	 ZERODHA ADVANCE BOT 
Current candel checking  no        14
Current Colour on this token is    none
Current Symbol                     GAIL
Data fetched ! compressing Data for indicator ...
5


 	 	 	 	 ZERODHA ADVANCE BOT 
Current candel checking  no        15
Current Colour on this token is    none
Current Symbol                     GRASIM
Data fetched ! compressing Data for indicator ...
5


 	 	 	 	 ZERODHA ADVANCE BOT 
Current candel checking  no        16
Current Colour on this token is    none
Current Symbol                     HCLTECH
Data fetched ! compressing Data for indicator ...
5


 	 	 	 	 ZERODHA ADVANCE BOT 
Current candel checking  no        17
Current Colour on this token is    none
Current Symbol                     HDFCBANK
Data fetched ! compressing Data for indicator ...
5


 	 	 	 	 ZERODHA ADVANCE BOT 
Current candel checking  no        18
Current Colour on this token is    none
Current Symbol                     HEROMOTOCO
Data fetched ! compressing Data for indicator ...
5


 	 	 	 	 ZERODHA ADVANCE BOT 
Current candel checking  no        19
Current Colour on this token is    green
Current Symbol                     HINDALCO
Data fetched ! compressing Data for indicator ...
BUY stock found 
5


 	 	 	 	 ZERODHA ADVANCE BOT 
Current candel checking  no        20
Current Colour on this token is    none
Current Symbol                     HINDUNILVR
Data fetched ! compressing Data for indicator ...
5


 	 	 	 	 ZERODHA ADVANCE BOT 
Current candel checking  no        21
Current Colour on this token is    none
Current Symbol                     HDFC
Data fetched ! compressing Data for indicator ...
5


 	 	 	 	 ZERODHA ADVANCE BOT 
Current candel checking  no        22
Current Colour on this token is    none
Current Symbol                     ICICIBANK
Data fetched ! compressing Data for indicator ...
5


 	 	 	 	 ZERODHA ADVANCE BOT 
Current candel checking  no        23
Current Colour on this token is    none
Current Symbol                     ITC
Data fetched ! compressing Data for indicator ...
5


 	 	 	 	 ZERODHA ADVANCE BOT 
Current candel checking  no        24
Current Colour on this token is    none
Current Symbol                     IBULHSGFIN
Data fetched ! compressing Data for indicator ...
5


 	 	 	 	 ZERODHA ADVANCE BOT 
Current candel checking  no        25
Current Colour on this token is    none
Current Symbol                     IOC
Data fetched ! compressing Data for indicator ...
5


 	 	 	 	 ZERODHA ADVANCE BOT 
Current candel checking  no        26
Current Colour on this token is    none
Current Symbol                     INDUSINDBK
Data fetched ! compressing Data for indicator ...
5


 	 	 	 	 ZERODHA ADVANCE BOT 
Current candel checking  no        27
Current Colour on this token is    none
Current Symbol                     INFY
Data fetched ! compressing Data for indicator ...
5


 	 	 	 	 ZERODHA ADVANCE BOT 
Current candel checking  no        28
Current Colour on this token is    none
Current Symbol                     JSWSTEEL
Data fetched ! compressing Data for indicator ...
5


 	 	 	 	 ZERODHA ADVANCE BOT 
Current candel checking  no        29
Current Colour on this token is    none
Current Symbol                     KOTAKBANK
Data fetched ! compressing Data for indicator ...
5


 	 	 	 	 ZERODHA ADVANCE BOT 
Current candel checking  no        30
Current Colour on this token is    none
Current Symbol                     LT
Data fetched ! compressing Data for indicator ...
5


 	 	 	 	 ZERODHA ADVANCE BOT 
Current candel checking  no        31
Current Colour on this token is    none
Current Symbol                     M&M
Data fetched ! compressing Data for indicator ...
5


 	 	 	 	 ZERODHA ADVANCE BOT 
Current candel checking  no        32
Current Colour on this token is    none
Current Symbol                     MARUTI
Data fetched ! compressing Data for indicator ...
5


 	 	 	 	 ZERODHA ADVANCE BOT 
Current candel checking  no        33
Current Colour on this token is    none
Current Symbol                     NTPC
Data fetched ! compressing Data for indicator ...
5


 	 	 	 	 ZERODHA ADVANCE BOT 
Current candel checking  no        34
Current Colour on this token is    none
Current Symbol                     ONGC
Data fetched ! compressing Data for indicator ...
5


 	 	 	 	 ZERODHA ADVANCE BOT 
Current candel checking  no        35
Current Colour on this token is    green
Current Symbol                     POWERGRID
Data fetched ! compressing Data for indicator ...
BUY stock found 
5


 	 	 	 	 ZERODHA ADVANCE BOT 
Current candel checking  no        36
Current Colour on this token is    none
Current Symbol                     RELIANCE
Data fetched ! compressing Data for indicator ...
5


 	 	 	 	 ZERODHA ADVANCE BOT 
Current candel checking  no        37
Current Colour on this token is    none
Current Symbol                     SBIN
Data fetched ! compressing Data for indicator ...
5


 	 	 	 	 ZERODHA ADVANCE BOT 
Current candel checking  no        38
Current Colour on this token is    none
Current Symbol                     SUNPHARMA
Data fetched ! compressing Data for indicator ...
5


 	 	 	 	 ZERODHA ADVANCE BOT 
Current candel checking  no        39
Current Colour on this token is    none
Current Symbol                     TCS
Data fetched ! compressing Data for indicator ...
5


 	 	 	 	 ZERODHA ADVANCE BOT 
Current candel checking  no        40
Current Colour on this token is    none
Current Symbol                     TATAMOTORS
Data fetched ! compressing Data for indicator ...
5


 	 	 	 	 ZERODHA ADVANCE BOT 
Current candel checking  no        41
Current Colour on this token is    none
Current Symbol                     TATASTEEL
Data fetched ! compressing Data for indicator ...
5


 	 	 	 	 ZERODHA ADVANCE BOT 
Current candel checking  no        42
Current Colour on this token is    none
Current Symbol                     TECHM
Data fetched ! compressing Data for indicator ...
5


 	 	 	 	 ZERODHA ADVANCE BOT 
Current candel checking  no        43
Current Colour on this token is    none
Current Symbol                     TITAN
Data fetched ! compressing Data for indicator ...
5


 	 	 	 	 ZERODHA ADVANCE BOT 
Current candel checking  no        44
Current Colour on this token is    none
Current Symbol                     UPL
Data fetched ! compressing Data for indicator ...
5


 	 	 	 	 ZERODHA ADVANCE BOT 
Current candel checking  no        45
Current Colour on this token is    none
Current Symbol                     ULTRACEMCO
Data fetched ! compressing Data for indicator ...
5


 	 	 	 	 ZERODHA ADVANCE BOT 
Current candel checking  no        46
Current Colour on this token is    none
Current Symbol                     VEDL
Data fetched ! compressing Data for indicator ...
5


 	 	 	 	 ZERODHA ADVANCE BOT 
Current candel checking  no        47
Current Colour on this token is    none
Current Symbol                     WIPRO
Data fetched ! compressing Data for indicator ...
5


 	 	 	 	 ZERODHA ADVANCE BOT 
Current candel checking  no        48
Current Colour on this token is    none
Current Symbol                     YESBANK
Data fetched ! compressing Data for indicator ...
5


 	 	 	 	 ZERODHA ADVANCE BOT 
Current candel checking  no        49
Current Colour on this token is    none
Current Symbol                     ZEEL
Data fetched ! compressing Data for indicator ...
 SCAN COMPLETED !!
'Sun, 01 Sep 2019 12:51:14 AM'
'Sun, 01 Sep 2019 12:52:02 AM'
BUY bid placed                     = []
Sell bid placed                    = []


BUY fail in backtesting            = []
SELL fail in backtesting           = []


BUY token ignored 'already placed' = []
SELL token ignored 'already placed'= []


Code Completed 
				
			
This multi-stock trading capability, combined with its persistent monitoring of the stock list, sets this bot apart from earlier versions, establishing a new benchmark.
Post a comment

Leave a Comment

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

×Close