Phyton

Created: October 9, 2025 at 6:27 am

Expires: Never

Syntax: Python

# -*- coding: utf-8 -*-
"""
Created on Mon Jun 10 06:12:22 2024

@author: Y S Chakravarthy 
Version: 2.0
"""

#--------------------IMPORT LIBRARIES Function Start---------------------------

import pya3
from pya3 import *
from time import sleep
from datetime import datetime as datetime2, timedelta
import datetime
import time as tm
import threading
import requests
import pandas as pd
import numpy as np
from datetime import timedelta
import pandas_ta as ta
import nsepy as ns
import openpyxl
import sys
import os,io
import warnings

import math
import matplotlib.pyplot as plt
import mplfinance as mpf
import json
from colorama import Fore, Style

from api_helper2 import ShoonyaApiPy
import pyotp
import contextlib

warnings.filterwarnings("ignore", category=RuntimeWarning)
warnings.filterwarnings("ignore", category=UserWarning)

#--------------------IMPORT LIBRARIES Function End---------------------------

#--------------------SUPRESS STDOUT Function Start---------------------------

def suppress_stdout():
    # Open /dev/null for writing to suppress output
    with open(os.devnull, 'w') as devnull:
        # Save the original stdout and replace it with /dev/null
        old_stdout = sys.stdout
        sys.stdout = devnull
        try:
            yield
        finally:
            # Restore the original stdout
            sys.stdout = old_stdout

#--------------------SUPRESS STDOUT Function End---------------------------

#--------------------EVENT HANDLER FEED UPDATE Function Start---------------------------

def event_handler_feed_update(tick_data):
    global LTP,strike_dict,v
    #print(f"feed update {tick_data}")
    if 'lp' in tick_data:
        LTP=tick_data['lp']  
  
        strike_dict[tick_data['tk']]=LTP
        v=tick_data['v']    

#--------------------EVENT HANDLER FEED UPDATE Function End---------------------------

#--------------------OPEN CALLBACK Function Start---------------------------
def open_callback():
    global feed_opened
    feed_opened = True
#--------------------OPEN CALLBACK Function End---------------------------

#--------------------SUBSCRIBE Function Start---------------------------
def subscribe():
    shoonya.subscribe(subscribe_list)
#--------------------SUBSCRIBE Function End---------------------------

#--------------------SOCKET_OPEN Function Start---------------------------

def socket_open():  # Socket open callback function
    print("Socket Connected")
    global socket_opened
    socket_opened = True
    if subscribe_flag:  # This is used to resubscribe the script when reconnect the socket.
        alice.subscribe(subscribe_list)

#--------------------SOCKET_OPEN Function End---------------------------

#--------------------SOCKET_CLOSE Function Start---------------------------

def socket_close():  # On Socket close this callback function will trigger
    global socket_opened, LTP
    socket_opened = False
    LTP = 0
    BID=0
    ASK=0
    print("Socket Closed")

#--------------------SOCKET_CLOSE Function End---------------------------

#--------------------SOCKET_ERROR Function Start---------------------------

def socket_error(message):  # Socket Error Message will receive in this callback function
    global LTP
    LTP = 0
    BID=0
    ASK=0
    print("Error :", message)

#--------------------SOCKET_ERROR Function End---------------------------

#--------------------FEED_DATA Function Start---------------------------

def feed_data(message):  # Socket feed data will receive in this callback function
    global LTP, BID, ASK, subscribe_flag,sheet,strike_dict,ce,pe,v
    
    feed_message = json.loads(message)
    if feed_message["t"] == "ck":
        #print("Connection Acknowledgement status :%s (Websocket Connected)" % feed_message["s"])
        subscribe_flag = True
        #print("subscribe_flag :", subscribe_flag)
        #print("-------------------------------------------------------------------------------")
        pass
    
    elif feed_message["t"] == "tk":
        #print("Token Acknowledgement status :%s " % feed_message)
        #print("-------------------------------------------------------------------------------")
        pass
    else:
        if 'lp' in feed_message:            
            LTP = feed_message['lp']
                            # If LTP in the response it will store in LTP variable
            strike_dict[feed_message['tk']]=LTP
        
        if 'v' in feed_message:
            if feed_message['tk'] == scrip_token:
                v=feed_message['v'] 
        else:
            pass
        
#--------------------FEED_DATA Function End---------------------------

#--------------------GET TOKEN Function Start---------------------------

def get_token(exch,query):
    ret = shoonya.searchscrip(exchange=exch, searchtext=query)
    
    if ret != None:
        symbols = ret['values']
        for symbol in symbols:      
            pass
            #print('{0} token is {1}'.format(symbol['tsym'], symbol['token']))
    return symbol['token'] 
#--------------------GET TOKEN Function Start---------------------------

#--------------------CURRENT WORKING DIRECTORY & PATH START---------------------------

warnings.filterwarnings("ignore", category=RuntimeWarning)
warnings.filterwarnings("ignore", category=UserWarning)
warnings.filterwarnings("ignore", category=FutureWarning)

# Print the current working directory
print("\nW Directory :", os.getcwd())

# Get the absolute path of the EXE file
exe_file_path = sys.argv[0]
print("File Path   :", os.path.abspath(exe_file_path))
print("File Name   :", os.path.basename(os.path.abspath(exe_file_path)).title())

#--------------------CURRENT WORKING DIRECTORY & PATH END---------------------------

#--------------------READDATA Function Start---------------------------

def readData(file, sheetName, rownum, columnno):
    workbook = openpyxl.load_workbook(file)
    sheet = workbook[sheetName]
    return sheet.cell(row=rownum, column=columnno).value


#--------------------READDATA Function End---------------------------

#-------------------- LOGIN Function Start---------------------------

def login():
    global x
    try:
        x=pd.read_json("shoonya_details.json",orient='index')    
    except ValueError:
        print("cannot read shoonya credentials") 
        
    user=x[0]['user']
    #print('\nUser-id :',user)
    pwd=x[0]['pwd']
    vc=x[0]['vc']
    app_key=x[0]['app_key']
    imei=x[0]['imei']
    code=x[0]['code'] # TOTP qr code (get it on the website under security settings)
    #multiplier=1
    api = ShoonyaApiPy()
    factor2 = pyotp.TOTP(code).now()
    ret=api.login(userid=user, password=pwd, twoFA=factor2, vendor_code=vc, api_secret=app_key, imei=imei)
    #print(ret)
    if ret == None:
        print("Cannot Login. Please check credentials\n")
        print("try the following steps:")  
        print("\n-Ensure that TOTP QR key is entered and not the 6 digit TOTP \n")
        print("-Stop any other Algo running on the same account\n")
        print("-Regenerate Api Keys\n")
        return None
    else:        
        if ret['stat'] == 'Ok':
                print("\nFinvasia Login Successful")
                return api  
#--------------------LOGIN Function End---------------------------

#--------------------MONTH NAME TO NUMBER Function Start---------------------------

def month_name_to_number(month_name):
    datetime_object = datetime.datetime.strptime(month_name, "%b")
    month_number = datetime_object.month
    return month_number

#--------------------MONTH NAME TO NUMBER Function End---------------------------

#--------------------SYSTEM PARAMETERS Function Start---------------------------

def system_parameters(mainfile):
    
    global exch, symbol, strategy_type, option_strategy, option_expiry, positions_file, sltp_inst
    global order, symbol_ist, timeframe, qty, option_exchange, strike_diff, tsl, price_step
    global buffer_pct,roundoff, underlying, moneyness, option_qty, candle_type, sl_step, lot_size
    global trading_mode, sl, tp, sltype, tptype, positional_trade, max_profit,max_loss,max_trades
    global start_time, end_time, exit_time, start_time2, end_time2, delta_end_time2, option_expiry
    
    order               = pd.read_excel(f'{mainfile}',sheet_name='order')
    symbol_list         = pd.read_excel(f'{mainfile}',sheet_name='symbol_list')
    
    buffer_pct          = 0
    roundoff            = 0
    exch                = order['Details'][0]
    symbol              = order['Details'][1]
    timeframe           = order['Details'][2]
    qty                 = order['Details'][3]
    underlying          = order['Details'][4]
    strategy_type       = order['Details'][5]
    option_strategy     = str(order['Details'][6])
    moneyness           = order['Details'][7]
    option_expiry       = str(order['Details'][8])
    
    option_exchange     = opt_exch_dict[exch]
    lot_size            = int(symbol_list[symbol_list['Symbol'] == underlying]['lot_size'].values[0])
    strike_diff         = int(symbol_list[symbol_list['Symbol'] == underlying]['Applicable Step value'].values[0])
    option_qty          = int(order['Details'][9])
    candle_type         = order['Details'][10]
    positional_trade    = order['Details'][13]
    positions_file      = f"{order['Details'][14]}.json"
    
    option_expiry = get_expiry_dates(option_exchange,underlying)
    starting_time()
    
    m=np.mod(start_time.minute,timeframe)
    if m != 0:
        print(f"start time is in intervals of {timeframe} minute\n")
        send_messages(f"start time is in intervals of {timeframe} minute\n",get_messages)
        start_time=start_time+timedelta(hours=0,minutes=int(timeframe-m))
        print(f"starting at next {timeframe} minute candle at {start_time.time()}\n")
        send_messages(f"starting at next {timeframe} minute candle at {start_time.time()}\n",get_messages)        
    else:
        pass
        
    ### READING TRADING DETAILS ###
    
    trading_mode=order.iloc[:,4][0]
    max_profit=float(order.iloc[:,4][2]) 
    max_loss=float(order.iloc[:,4][3]) 
    
    max_trades=float(order.iloc[:,4][4])
    
    
    if max_profit > 0:
        max_profit
    else:
        max_profit = 0
    
    if max_loss < 0:
        max_loss
    else:
        max_loss = 0
    
    if max_trades > 0:
        max_trades
    else:
        max_trades = 0
    
    ### READING SLTP DETAILS ### 
    sltp_inst=str(order.iloc[:,6][0].upper())
    sltype=str(order.iloc[:,6][1])
    tptype=str(order.iloc[:,6][2])
    sl=float(order.iloc[:,6][3])
    tp=float(order.iloc[:,6][4])
    tsl=str(order.iloc[:,6][5].upper())
    price_step=float(order.iloc[:,6][6])
    sl_step=float(order.iloc[:,6][7])
    

    if strategy_type == 1 and sltp_inst == 'OPTION':
        print("selecting SLTP instrument as SYMBOL")
        send_messages("selecting SLTP instrument as SYMBOL",get_messages)
        sltp_inst = 'SYMBOL'
      
#--------------------SYSTEM PARAMETERS Function End---------------------------

#--------------------STARTING TIME Function End---------------------------

def starting_time():    
    
    global start_time, end_time, exit_time, start_time2, end_time2,end_time3, delta_end_time2, no_trade_time, option_expiry_day
    
    option_expiry_year  = readData(mainfile, 'Get_Symbol', 3, 5)
    month_name          = readData(mainfile, 'Get_Symbol', 4, 5)
    option_expiry_month = month_name_to_number(month_name)
    #option_expiry_day   = readData(mainfile, 'Get_Symbol', 5, 5)
    op_exp_year         = int('20'+str(option_expiry_year))

    current_time        = datetime2.now()
    rounded_minutes     = ((current_time.minute // timeframe) + 1) * timeframe
    if rounded_minutes  == 60:
        rounded_minutes = 0
        current_time    += timedelta(hours=1)
    start_time          = current_time.replace(minute=rounded_minutes, second=0, microsecond=0)
    
    if exch=='MCX':
        scheduled_time      = current_time.replace(hour = 9, minute = 0, second = 0, microsecond = 0)
    else:    
        scheduled_time      = current_time.replace(hour = 9, minute = 15, second = 0, microsecond = 0)
    
    if scheduled_time   > start_time:
        start_time      = scheduled_time
        
    end_time            = start_time+timedelta(minutes=timeframe)   # timeframe of the candle  
    
    if exch=='MCX':
        #exit_time=current_time.replace(hour=23,minute=25,second=0,microsecond=0)
        exit_time       = current_time.replace(year=op_exp_year,month=option_expiry_month,day=int(option_expiry_day),hour=23,minute=25,second=0,microsecond=0)
        no_trade_time   = current_time.replace(year=op_exp_year,month=option_expiry_month,day=int(option_expiry_day),hour=23,minute=00,second=0,microsecond=0)
    else:
        #exit_time=current_time.replace(hour=15,minute=25,second=0,microsecond=0)
        exit_time       = current_time.replace(year=op_exp_year,month=option_expiry_month,day=int(option_expiry_day),hour=15,minute=25,second=0,microsecond=0)
        no_trade_time   = current_time.replace(year=op_exp_year,month=option_expiry_month,day=int(option_expiry_day),hour=15,minute=00,second=0,microsecond=0)
        
    #start_time=datetime.strptime(str(order['details'][11]),'%H:%M:%S')
    #exit_time=datetime.strptime(str(order['details'][12]),'%H:%M:%S')

    start_time2         = start_time
    delta_end_time2     = timedelta(seconds=10) 
    end_time2           = start_time2+delta_end_time2
    end_time3           = start_time+timedelta(minutes=timeframe)
    
#--------------------STARTING TIME Function End---------------------------

#--------------------GET HISTORY Function Start---------------------------

def get_history(instrument,interval,from_datetime,to_datetime):
    global indices,pdh,pdl,pdc
    if order['Details'][0] == 'INDICES':        
        indices = True # For Getting index data
    else:
        indices = False
    try:            
        data=alice.get_historical(instrument, from_datetime, to_datetime, interval, indices)
        ret = shoonya.get_time_price_series(exchange=exch, token=str(tk), starttime=lastBusDay.timestamp(),interval=timeframe)
       
    except AttributeError:
        pass
    except json.JSONDecodeError:
        print('\nPlease Login into Aliceblue web page using the link below and try again')
        print(f'{Fore.RED}https://ant.aliceblueonline.com/{Style.RESET_ALL}')
    
    try:
        data.empty == True      
    except UnboundLocalError:
        print("\nCannot retrieve data. Make sure to login to alice blue web portal & enter a valid Symbol-Exchange combination\n")
        print("Refer to the symbol & expiry format here: \n")
        print(f"{Fore.RED}https://docs.google.com/spreadsheets/d/1igGRn0-O4Mvvsh4zwV-ADGgXLnv2Ryxe/edit?usp=sharing&ouid=107379272605685200998&rtpof=true&sd=true{Style.RESET_ALL}")
        
        tm.sleep(10)
    else:
        
        pdh,pdl,pdc,pdo=PDH_PDL(indices)
        data['datetime'] = pd.to_datetime(data['datetime'])
        data.set_index('datetime', inplace=True)
        
        op=data['open'].resample(f'{timeframe}T').first()
        cl=data['close'].resample(f'{timeframe}T').last()
        high=data['high'].resample(f'{timeframe}T').max()
        low=data['low'].resample(f'{timeframe}T').min()
        vol=data['volume'].resample(f'{timeframe}T').sum()   
        
        ohlc=pd.DataFrame(columns=['open','high','low','close','volume'])
        ohlc['open']=op
        ohlc['close']=cl
        ohlc['high']=high
        ohlc['low']=low
        ohlc['volume']=vol
        ohlc=ohlc.dropna()
        data=ohlc
        
        if candle_type=='ha':
            data=convert_to_heikin_ashi(data)            
        else:
            pass   
        
        return data
    
#--------------------GET HISTORY Function End---------------------------

#--------------------PDH PDL Function Start---------------------------

def PDH_PDL(indices):
    
    data_day=alice.get_historical(instrument, from_datetime, to_datetime, "D", indices)
    data_day['datetime']=pd.to_datetime(data_day['datetime'])
    if data_day['datetime'][len(data_day)-1].date() < datetime2.now().date():
        PDH=data_day['high'][len(data_day)-1]
        PDL=data_day['low'][len(data_day)-1]
        PDC=data_day['close'][len(data_day)-1]
        PDO=data_day['open'][len(data_day)-1]
    else:
        PDH=data_day['high'][len(data_day)-2]
        PDL=data_day['low'][len(data_day)-2]
        PDC=data_day['close'][len(data_day)-2]
        PDO=data_day['open'][len(data_day)-2]
        
    return PDH,PDL,PDC,PDO

#--------------------PDH PDL Function End---------------------------

#--------------------CONVERT TO HA Function Start-----------------------------------

def convert_to_heikin_ashi(df):
    
    df2=df.filter(['open','high','low','close','volume'])
    ha_df = pd.DataFrame(index=df2.index, columns=df2.columns)
    ha_df['open'] = (df2['open'].shift(1) + df2['close'].shift(1)) / 2
    ha_df['close'] = (df2['open'] + df2['high'] + df2['low'] + df2['close']) / 4
    ha_df['volume'] = df2.volume
    ha_df['h']=df2.high
    ha_df['l']=df2.low
    
    for i in range(2, len(df2)):
        ha_df.at[df2.index[i], 'open'] = (ha_df.at[df2.index[i-1], 'open'] + ha_df.at[df2.index[i-1], 'close']) / 2
        #ha_df.at[df2.index[i], 'close'] = (df2.at[df2.index[i], 'open'] + df2.at[df2.index[i], 'high'] + df2.at[df2.index[i], 'low'] + df2.at[df2.index[i], 'close']) / 4

    ha_df['high'] = ha_df[['open', 'close','h']].max(axis=1)
    ha_df['low'] = ha_df[['open', 'close'   ,'l']].min(axis=1)
    
    # Remove the first row with NaN values    
    ha_df = ha_df.dropna()
    
    return ha_df

#--------------------CONVERT TO HA Function End-----------------------------------

#--------------------GET EXPIRY DATES Function Start-----------------------------------

def get_expiry_dates(option_exchange,underlying):
    
    global months, option_expiry_day

    if option_exchange == "NFO":
                
                #print("\nDownloading latest NFO contracts")
                
                contracts=requests.get('https://v2api.aliceblueonline.com/restpy/static/contract_master/NFO.csv')                  
                csv_stream = io.StringIO(contracts.content.decode('utf-8'))         
                d=pd.read_csv(csv_stream)
      
                
                
                if option_expiry == "CURRENT_WEEK":
                    
                    expiries=sorted(d[d['Symbol'] == underlying]['Expiry Date'].drop_duplicates())
                    expiry=datetime2.strptime(expiries[0], '%Y-%m-%d')
                    parts = expiries[0].split('-')
                    expiry = parts[2] + months[parts[1]] + parts[0][2:]
                    
                if option_expiry == "NEXT_WEEK":
                    
                    expiries=sorted(d[d['Symbol'] == underlying]['Expiry Date'].drop_duplicates())
                    expiry=datetime2.strptime(expiries[1], '%Y-%m-%d')
                    parts = expiries[1].split('-')
                    expiry = parts[2] + months[parts[1]] + parts[0][2:]
                
                if option_expiry == "CURRENT_MONTH":
                    
                    expiries=sorted(d[(d['Symbol'] == underlying) & (d['Option Type'] == "XX")]['Expiry Date'].drop_duplicates())
                    expiry=datetime2.strptime(expiries[1], '%Y-%m-%d')
                    parts = expiries[0].split('-')
                    expiry = parts[2] + months[parts[1]] + parts[0][2:]
                    
                if option_expiry == "NEXT_MONTH":
                    
                    expiries=sorted(d[(d['Symbol'] == underlying) & (d['Option Type'] == "XX")]['Expiry Date'].drop_duplicates())
                    expiry=datetime2.strptime(expiries[1], '%Y-%m-%d')
                    parts = expiries[1].split('-')
                    expiry = parts[2] + months[parts[1]] + parts[0][2:]
                    
    if option_exchange == "MCX":   
                 
                #print("\nDownloading latest MCX contracts")
                
                contracts=requests.get('https://v2api.aliceblueonline.com/restpy/static/contract_master/MCX.csv')                  
                csv_stream = io.StringIO(contracts.content.decode('utf-8'))         
                d=pd.read_csv(csv_stream)
      
                if option_expiry == "CURRENT_MONTH" or option_expiry == "CURRENT_WEEK":
                    
                    expiries=sorted(d[(d['Symbol'] == underlying) & (d['Option Type'] == "CE")]['Expiry Date'].drop_duplicates())
                    expiry=datetime2.strptime(expiries[0], '%Y-%m-%d')
                    parts = expiries[0].split('-')
                    expiry = parts[2] + months[parts[1]] + parts[0][2:]
                    
                elif option_expiry == "NEXT_MONTH" or option_expiry == "NEXT_WEEK":
                    
                    expiries=sorted(d[(d['Symbol'] == underlying) & (d['Option Type'] == "CE")]['Expiry Date'].drop_duplicates())
                    expiry=datetime2.strptime(expiries[1], '%Y-%m-%d')
                    parts = expiries[1].split('-')
                    expiry = parts[2] + months[parts[1]] + parts[0][2:]
                    
    option_expiry_day = parts[2]              
    return expiry

#--------------------GET EXPIRY DATES Function End-----------------------------------

#--------------------GET STRIKES Function Start-----------------------------------

def get_strikes(fut_price,strike_diff):    
    n=np.mod(fut_price,strike_diff)
    if n<(strike_diff/2):
        atm_strike=int(fut_price-n)
    else:
        atm_strike=int(fut_price-n)+strike_diff

    return atm_strike

#--------------------GET STRIKES Function End-----------------------------------

#--------------------GET OPTION INSTRUMENTS Function Start-----------------------------------

def get_option_instruments(atm_strike,underlying,option_expiry,multiplier):

    calls=[]    
    puts=[]
    strike=atm_strike - 6*(strike_diff)  
    
    while strike < (atm_strike + (strike_diff*multiplier)):
        inst=f'{underlying}{option_expiry}C{strike}'
        tk = get_token(exch, inst)
        call = (f'{exch}|{tk}')
        calls.append(call)
        strike=strike+strike_diff
        
    strike=atm_strike + 6*(strike_diff)  

    while strike > (atm_strike - (strike_diff*multiplier)):
        inst=f'{underlying}{option_expiry}P{strike}'
        tk = get_token(exch, inst)
        put=(f'{exch}|{tk}')
        puts.append(put)
        strike=strike-strike_diff
        
    return calls,puts    

#--------------------GET OPTION INSTRUMENTS Function End-----------------------------------

#--------------------GET PRODUCT TYPE Function Start-----------------------------------

def get_product_type():
    if exch=='NSE':         
        if strategy_type==1:
            if positional_trade=="YES":
                product_type=ProductType.Delivery
            elif positional_trade=="NO":
                product_type=ProductType.Intraday
        elif strategy_type==2:        
            product_type = ProductType.Normal
            
    if exch=='NFO':
        product_type = ProductType.Normal
        
    if exch=='MCX':    
        product_type = ProductType.Normal
        
    elif exch == 'INDICES':
        product_type = ProductType.Normal
    return product_type    

#--------------------GET PRODUCT TYPE Function End-----------------------------------

#--------------------SEND MESSAGES Function Start-----------------------------------

def send_messages(message,get_messages):
    if get_messages.upper() == "YES":
        base_url=f'https://api.telegram.org/bot{bot_token}/sendMessage?chat_id={chat_id}'             
        msg_url=f'&text={message}'
        main_url=base_url+msg_url
        requests.get(main_url)

#--------------------SEND MESSAGES Function End-----------------------------------

#--------------------STORE POSITIONS Function Start-----------------------------------

def store_positions(exch,symbol,trade,qty,price,stoploss,target,orderid,index):
    aDict = {"exchange":exch,"symbol":symbol,"position":trade,"qty":qty,"price":price,'sl':stoploss,'tp':target, 'orderid':orderid, 'index_m':index}
    jsonString = json.dumps(aDict)
    jsonFile = open(positions_file, "w+")
    jsonFile.write(jsonString)
    jsonFile.close()

#--------------------STORE POSITIONS Function End-----------------------------------

#--------------------MTM EXIT Function Start-----------------------------------

def mtm_exit():
    global net_pnl,net_realized,unrealized,check_mtm
    
    try:
        if check_mtm == False:
            if trade ==1:
                if strategy_type == 1:
                    unrealized_pnl=(float(strike_dict[scrip_token]) - last_buy_price)*qty
                elif strategy_type == 2:   
                    
                    if sltp_inst == 'SYMBOL':
                        if option_strategy == "BUY":
                            unrealized_pnl=(float(strike_dict[op_token]) - last_buy_price)*option_qty
                        if option_strategy == "SELL":
                            unrealized_pnl=(last_buy_price-float(strike_dict[op_token]))*option_qty
                    
                    if sltp_inst == 'OPTION':
                        if option_strategy == "BUY":
                            unrealized_pnl=(float(strike_dict[op_token]) - last_buy_price)*option_qty
                        if option_strategy == "SELL":
                            unrealized_pnl=(last_buy_price-float(strike_dict[op_token]))*option_qty
                           
                           
                    
                net_pnl=net_realized+unrealized_pnl
                if net_pnl >= max_profit and max_profit > 0:
                    print("Max daily profit reached")
                    send_messages("Max daily profit reached",get_messages)
                    universal_exit()
                    check_mtm=True
                    sys.exit()
                    
                elif net_pnl <= max_loss and max_loss < 0:
                    print("Max daily loss reached")
                    send_messages("Max daily loss reached",get_messages)
                    universal_exit()   
                    check_mtm=True
                    sys.exit()
                
            elif trade ==-1:
                
                if strategy_type == 1:
                    unrealized_pnl=(last_sell_price-float(strike_dict[scrip_token]))*qty
                elif strategy_type == 2:   
                    if option_strategy == "BUY":
                        unrealized_pnl=(float(strike_dict[op_token]) - last_sell_price)*option_qty
                    if option_strategy == "SELL":
                        unrealized_pnl=(last_sell_price-float(strike_dict[op_token]))*option_qty
        
                net_pnl=net_realized+unrealized_pnl
                if net_pnl >= max_profit and max_profit > 0:
                    print("Max daily profit reached")
                    send_messages("Max daily profit reached",get_messages)
                    universal_exit()
                    check_mtm=True
                    sys.exit()
                    
                elif net_pnl <= max_loss and max_loss < 0:
                    print("Max daily loss reached")
                    send_messages("Max daily loss reached",get_messages)
                    universal_exit() 
                    check_mtm=True
                    sys.exit()
    except:
        pass
    threading.Timer(1,mtm_exit).start()

#--------------------MTM EXIT Function End-----------------------------------

#--------------------TRAILING STOP Function Start-----------------------------------

def trailing_stop(price_step,sl_step):
    
    global buy_sl,sell_sl,prev_buy_step,prev_sell_step, op, orderid, inst, option_qty, exch
    global last_buy_price, last_sell_price
    """    
    if strategy_type == 1:
        try:
            price = float(alice.get_scrip_info(instrument)['LTP'])
        except KeyError:
            price = prev_buy_step 
    
    if trade == -1 and strategy_type == 2:
        try:
            price = float(alice.get_scrip_info(op)['LTP'])
        except KeyError:
            price = prev_buy_step    
    """    
    if trade == 1:
        
        if strategy_type == 1:
            try:
                price = float(alice.get_scrip_info(instrument)['LTP'])
            except KeyError:
                price = prev_buy_step
        else:
            try:
                tk = get_token(exch, op_symbol)
                price = float(shoonya.get_quotes(exchange=exch, token=tk)['lp'])
            except KeyError:
                price = prev_buy_step
        
        if strategy_type == 2:
            if option_strategy == "BUY":    
                
                if price         >= (last_buy_price + (sl/2)) and buy_sl < last_buy_price:
                    buy_sl        = last_buy_price
                    prev_buy_step = last_buy_price  + (sl/2)
                    pres_price    = last_buy_price + math.floor(price - last_buy_price)
                    #----------------------------------------------------
                    buy_id, buy_exit = modify_sl_sell_orders(orderid, op, buy_sl, option_qty, exch)
                    store_positions(option_exchange, op_symbol, trade, option_qty, buy_entry, buy_sl, buy_tp, orderid, index)
                    #----------------------------------------------------
                    
                    print("Buy SL trailed to: %.2f, Entry: %.2f, CMP: %.2f, PnL: %.2f, Time: %s"%(buy_sl,last_buy_price,price,(pres_price - last_buy_price)*option_qty,datetime2.now().time().replace(microsecond=0)))
                    send_messages("Buy SL trailed to: %.2f, Entry: %.2f, CMP: %.2f, PnL: %.2f, Time: %s"%(buy_sl,last_buy_price,price,(pres_price - last_buy_price)*option_qty,datetime2.now().time().replace(microsecond=0)),get_messages)
                    tm.sleep(1)
                    
                if price         >= (prev_buy_step + price_step):     
                    diff          = price          - prev_buy_step
                    buy_sl        = buy_sl         + math.floor(diff)
                    prev_buy_step = prev_buy_step  + math.floor(diff)
                    
                    #----------------------------------------------------
                    buy_id, buy_exit = modify_sl_sell_orders(orderid, op_symbol, buy_sl, option_qty, exch)
                    store_positions(option_exchange, op_symbol, trade, option_qty, buy_entry, buy_sl, buy_tp, orderid, index)
                    #----------------------------------------------------
                    
                    print("Buy SL trailed to: %.2f, Entry: %.2f, CMP: %.2f, PnL: %.2f, Time: %s"%(buy_sl,last_buy_price,price,(prev_buy_step - last_buy_price)*option_qty,datetime2.now().time().replace(microsecond=0)))
                    send_messages("Buy SL trailed to: %.2f, Entry: %.2f, CMP: %.2f, PnL: %.2f, Time: %s"%(buy_sl,last_buy_price,price,(prev_buy_step - last_buy_price)*option_qty,datetime2.now().time().replace(microsecond=0)),get_messages)
            
            if option_strategy == "SELL":
                
                if price         <= (prev_sell_step - price_step):
                    diff          = prev_sell_step  - price
                    sell_sl       = sell_sl        - math.floor(diff)
                    prev_sell_step = prev_sell_step  - math.floor(diff)
                    
                    print("Buy SL trailed to %.2f"%sell_sl)
                    send_messages("Buy SL trailed to %.2f"%sell_sl,get_messages)
        else:
            
            if price         >= (prev_buy_step + price_step):
                diff          = price          - prev_buy_step
                buy_sl        = buy_sl         + math.floor(diff)
                prev_buy_step = prev_buy_step  + math.floor(diff)
                
                print("Buy SL trailed to %.2f"%buy_sl)
                send_messages("Buy SL trailed to %.2f"%buy_sl,get_messages)
                
    if trade == -1:
        
        if strategy_type == 1:
            try:
                price = float(alice.get_scrip_info(instrument)['LTP'])
            except KeyError:
                price = prev_sell_step
        else:
            try:
                tk=get_token(exch, op_symbol)
                price = float(shoonya.get_quotes(exchange=exch, token=tk)['lp'])
            except KeyError:
                price = prev_sell_step
        
        if strategy_type == 2:
            
            if option_strategy == "BUY":   
                
                if price         >= (last_sell_price + (sl/2)) and buy_sl < last_sell_price:
                    buy_sl        = last_sell_price
                    prev_buy_step = last_sell_price  + (sl/2)
                    pres_price    = last_sell_price + math.floor(price - last_sell_price)
                    #----------------------------------------------------
                    sell_id, sell_exit = modify_sl_sell_orders(orderid, op_symbol, buy_sl, option_qty, exch)
                    store_positions(option_exchange, op_symbol, trade, option_qty, sell_entry, buy_sl, buy_tp, orderid, index)
                    #----------------------------------------------------
                    
                    print("Sell SL trailed to: %.2f, Entry: %.2f, CMP: %.2f, PnL: %.2f, Time: %s"%(buy_sl,last_sell_price,price,(pres_price - last_sell_price)*option_qty,datetime2.now().time().replace(microsecond=0)))
                    send_messages("Sell SL trailed to: %.2f, Entry: %.2f, CMP: %.2f, PnL: %.2f, Time: %s"%(buy_sl,last_sell_price,price,(pres_price - last_sell_price)*option_qty,datetime2.now().time().replace(microsecond=0)),get_messages)
                    tm.sleep(1)
                    
                if price          >= (prev_sell_step + price_step):
                    diff           = price           - prev_sell_step
                    buy_sl         = buy_sl          + math.floor(diff)
                    prev_sell_step = prev_sell_step  + math.floor(diff)
                    
                    #----------------------------------------------------
                    sell_id, sell_exit = modify_sl_sell_orders(orderid,op_symbol,buy_sl,option_qty,exch)
                    store_positions(option_exchange, op_symbol, trade, option_qty, sell_entry, buy_sl, buy_tp, orderid, index)
                    #----------------------------------------------------
                    
                    print("Sell SL trailed to: %.2f, Entry: %.2f, CMP: %.2f, PnL: %.2f, Time: %s"%(buy_sl,last_sell_price,price,(prev_sell_step - last_sell_price)*option_qty,datetime2.now().time().replace(microsecond=0)))
                    send_messages("Sell SL trailed to: %.2f, Entry: %.2f, CMP: %.2f, PnL: %.2f, Time: %s"%(buy_sl,last_sell_price,price,(prev_sell_step - last_sell_price)*option_qty,datetime2.now().time().replace(microsecond=0)),get_messages)
            
            if option_strategy == "SELL":
                
                if price          <= (prev_sell_step - price_step):
                    diff           = prev_sell_step  - price
                    sell_sl        = sell_sl         - math.floor(diff)
                    prev_sell_step = prev_sell_step  - math.floor(diff)
                    
                    print("Sell SL trailed to %.2f"%sell_sl)
                    send_messages("Sell SL trailed to %.2f"%sell_sl,get_messages)
        else:
            
            if price          <= (prev_sell_step - price_step):
                diff           = prev_sell_step  - price
                sell_sl        = sell_sl         - math.floor(diff)
                prev_sell_step = prev_sell_step  - math.floor(diff)
                
                print("Sell SL trailed to %.2f"%sell_sl)
                send_messages("Sell SL trailed to %.2f"%sell_sl,get_messages)
    
#--------------------TRAILING STOP Function End-----------------------------------

#--------------------SL EXIT Function Start-----------------------------------

def sl_exit():
    
    global trade,buy_entry,sell_entry,buy_sl,sell_sl,buy_tp,sell_tp,price, qty, orderid
    
    
    try:
        if strategy_type == 2:
            
            if sltp_inst == "OPTION":
                
                tk = get_token(exch, op_symbol)
                price=float(shoonya.get_quotes(exchange=exch, token=tk)['lp'])
  
            else:
                price=float(strike_dict[scrip_token])

        else:
            price=float(strike_dict[scrip_token])
    except:
        price=0
        pass
    
    if exit_ctr==False:
        if price>0:
            
            if trade==1:
                
                #buy_sltp(sl,tp)
                #pnl=(index-buy_entry)*qty            
                if strategy_type==1:    
                    
                    #if price <= buy_sl:
                    ord_stat = (alice.get_order_history(orderid)['Status'])
                    if ord_stat == 'complete':
                            buy_exit = float(alice.get_order_history(orderid)['Avgprc'])
                            print("\nBuy SL hit at %.2f"%(buy_exit))
                            send_messages("\nBuy SL hit at %.2f"%(buy_exit),get_messages)
                            
                            if exch=='MCX':
                                realized_pnl=(last_buy_price - buy_exit)*option_qty
                            else:    
                                realized_pnl=(last_buy_price - buy_exit)*option_qty
                            if realized_pnl < 0:
                                print("Current Trade realized profit : %.2f\n" % abs(realized_pnl))
                                send_messages("Current Trade realized profit : %.2f\n" % abs(realized_pnl), get_messages)
                            else:    
                                print("Current Trade realized loss : %.2f\n" % abs(realized_pnl))
                                send_messages("Current Trade realized loss : %.2f\n" % abs(realized_pnl), get_messages)
                            
                            
                        
                            #daily_pnl.append(realized_pnl)
                            #net_realized=np.sum(daily_pnl)
                            #print(f"Daywise realized pnl: {net_realized}\n")
                            #send_messages(f"Daywise realized pnl: {net_realized}\n",get_messages)
                        
                            buy_entry=0
                            sell_entry=0
                            buy_sl=0
                            buy_tp=0
                            trade=0
                        
                            store_positions(0,0,0,0,0,0,0,0,0)
                            save_positions(instrument[3],"SELL",buy_exit,qty)
                            
                            #--------------------------------------------------------------------
                           
                            day_NFO_PNL, day_MCX_PNL = Calculate_PNL()
                            today_pnl = day_NFO_PNL + day_MCX_PNL
                            
                            print("Today's NFO PnL: %.2f" % day_NFO_PNL)
                            print("Today's MCX PnL: %.2f" % day_MCX_PNL)
                            print("Today's All PnL: %.2f\n" % today_pnl)
                            
                            send_messages("Today's NFO PnL: %.2f {% day_NFO998_PNL}",get_messages)
                            send_messages("Today's MCX PnL: %.2f {% day_MCX_PNL}",get_messages)
                            send_messages("Today's All PnL: %.2f {% today_pnl}\n",get_messages)
                            
                            #--------------------------------------------------------------------
                            
                            if daily_trades >= max_trades and max_trades > 0:
                                print("Maximum daily trades reached. Stopping Algo")
                                send_messages("Maximum daily trades reached. Stopping Algo",get_messages)
                                tm.sleep(15)
                                sys.exit()
                    
                    if price < buy_sl:    
                        alice.cancel_order(orderid)
                        buy_sq_id, buy_exit = place_sell_orders(instrument,'',qty,exch,buffer_pct,roundoff)
                    
                        print("\nBuy Target hit at %.2f" % buy_exit)
                        send_messages("\nBuy Target hit at %.2f" % buy_exit,get_messages)
                        #print("Buy Trade Squaredoff at %.2f" % buy_exit)
                        #send_messages("Buy Trade Squaredoff at %.2f" % buy_exit,get_messages)
                        
                        if exch=='MCX':
                            realized_pnl=(last_buy_price - buy_exit)*option_qty
                        else:    
                            realized_pnl=(last_buy_price - buy_exit)*option_qty
                        if realized_pnl < 0:
                            print("Current Trade realized profit : %.2f\n" % abs(realized_pnl))
                            send_messages("Current Trade realized profit : %.2f\n" % abs(realized_pnl), get_messages)
                        else:    
                            print("Current Trade realized loss : %.2f\n" % abs(realized_pnl))
                            send_messages("Current Trade realized loss : %.2f\n" % abs(realized_pnl), get_messages)
                        
                        #--------------------------------------------------------------------
                       
                        day_NFO_PNL, day_MCX_PNL = Calculate_PNL()
                        today_pnl = day_NFO_PNL + day_MCX_PNL
                        
                        print("Today's NFO PnL: %.2f" % day_NFO_PNL)
                        print("Today's MCX PnL: %.2f" % day_MCX_PNL)
                        print("Today's All PnL: %.2f\n" % today_pnl)
                        
                        send_messages("Today's NFO PnL: %.2f {% day_NFO998_PNL}",get_messages)
                        send_messages("Today's MCX PnL: %.2f {% day_MCX_PNL}",get_messages)
                        send_messages("Today's All PnL: %.2f {% today_pnl}\n",get_messages)
                        
                        #--------------------------------------------------------------------
                    
                        #daily_pnl.append(realized_pnl)
                        #net_realized=np.sum(daily_pnl)
                        #print(f"Daywise realized pnl: {net_realized}\n")
                        #send_messages(f"Daywise realized pnl: {net_realized}\n",get_messages)
                    
                        buy_entry=0
                        sell_entry=0
                        buy_sl=0
                        buy_tp=0
                        trade=0
                    
                        store_positions(0,0,0,0,0,0,0,0,0)
                        
                        if daily_trades >= max_trades and max_trades > 0:
                            print("Maximum daily trades reached. Stopping Algo")
                            send_messages("Maximum daily trades reached. Stopping Algo",get_messages)
                            tm.sleep(15)
                            sys.exit()
                
                    if price >= buy_tp:
                        alice.cancel_order(orderid)
                        buy_sq_id, buy_exit = place_sell_orders(instrument,'',qty,exch,buffer_pct,roundoff)
                    
                        print("\nBuy Target hit at %.2f" % buy_exit)
                        send_messages("\nBuy Target hit at %.2f" % buy_exit,get_messages)
                        #print("Buy Trade Squaredoff at %.2f" % buy_exit)
                        #send_messages("Buy Trade Squaredoff at %.2f" % buy_exit,get_messages)
                        
                        if exch=='MCX':
                            realized_pnl=(buy_exit - last_buy_price)*qty
                        else:    
                            realized_pnl=(buy_exit - last_buy_price)*qty
                        
                        print("Current Trade realized profit : %.2f\n" % abs(realized_pnl))
                        send_messages("Current Trade realized profit : %.2f\n" % abs(realized_pnl), get_messages)
                        
                        #--------------------------------------------------------------------
                       
                        day_NFO_PNL, day_MCX_PNL = Calculate_PNL()
                        today_pnl = day_NFO_PNL + day_MCX_PNL
                        
                        print("Today's NFO PnL: %.2f" % day_NFO_PNL)
                        print("Today's MCX PnL: %.2f" % day_MCX_PNL)
                        print("Today's All PnL: %.2f\n" % today_pnl)
                        
                        send_messages("Today's NFO PnL: %.2f {% day_NFO998_PNL}",get_messages)
                        send_messages("Today's MCX PnL: %.2f {% day_MCX_PNL}",get_messages)
                        send_messages("Today's All PnL: %.2f {% today_pnl}\n",get_messages)
                        
                        #--------------------------------------------------------------------
                        
                        #daily_pnl.append(realized_pnl)
                        #net_realized=np.sum(daily_pnl)
                        #print(f"Daywise realized pnl: {net_realized}\n")
                        #send_messages(f"Daywise realized pnl: {net_realized}\n",get_messages)
                        
                        buy_entry=0
                        sell_entry=0
                        buy_sl=0
                        buy_tp=0
                        trade=0
                        
                        store_positions(0,0,0,0,0,0,0,0,0)
                        
                        if daily_trades >= max_trades and max_trades > 0:
                            print("Maximum daily trades reached. Stopping Algo")
                            send_messages("Maximum daily trades reached. Stopping Algo",get_messages)
                            tm.sleep(15)
                            sys.exit()
                
                elif strategy_type==2:
                    
                    if option_strategy.upper() == "SELL":
                    
                        if sltp_inst=='OPTION':
                            
                            #if price >= sell_sl:
                                ord_stat = (alice.get_order_history(orderid)['Status'])
                                if ord_stat == 'complete':
                                        buy_exit = float(alice.get_order_history(orderid)['Avgprc'])
                                        print("\nBuy SL hit at %.2f"%(buy_exit))
                                        send_messages("\nBuy SL hit at %.2f"%(buy_exit),get_messages)
                                        
                                        if exch=='MCX':
                                            realized_pnl=(last_buy_price - buy_exit)*option_qty
                                        else:    
                                            realized_pnl=(last_buy_price - buy_exit)*option_qty
                                        if realized_pnl > 0:
                                            print("Current Trade realized profit : %.2f\n" % abs(realized_pnl))
                                            send_messages("Current Trade realized profit : %.2f\n" % abs(realized_pnl), get_messages)
                                        else:    
                                            print("Current Trade realized loss : %.2f\n" % abs(realized_pnl))
                                            send_messages("Current Trade realized loss : %.2f\n" % abs(realized_pnl), get_messages)
                                        
                                        buy_entry=0
                                        sell_entry=0
                                        buy_sl=0
                                        buy_tp=0
                                        trade=0
                                
                                        store_positions(0,0,0,0,0,0,0,0,0)
                                        save_positions(op[3],"BUY",buy_exit,qty)
                                        
                                        if daily_trades >= max_trades and max_trades > 0:
                                            print("Maximum daily trades reached. Stopping Algo")
                                            send_messages("Maximum daily trades reached. Stopping Algo",get_messages)
                                            tm.sleep(15)
                                            sys.exit()
                                
                                if price > sell_sl:
                                    alice.cancel_order(orderid)
                                    buy_sq_id, buy_exit = place_buy_orders(op,'',option_qty,option_exchange,buffer_pct,roundoff)
                                    
                                    print("\nBuy Target hit at %s"%(buy_exit))
                                    send_messages("\nBuy Target hit at %s"%(buy_exit),get_messages)
                                    #print("Buy Trade Squaredoff at %.2f" % sell_exit)
                                    #send_messages("Buy Trade Squaredoff at %.2f" % sell_exit,get_messages)
                                    
                                    if exch=='MCX':
                                        realized_pnl=(last_buy_price - buy_exit)*option_qty
                                    else:    
                                        realized_pnl=(last_buy_price - buy_exit)*option_qty
                                    if realized_pnl > 0:
                                        print("Current Trade realized profit : %.2f\n" % abs(realized_pnl))
                                        send_messages("Current Trade realized profit : %.2f\n" % abs(realized_pnl), get_messages)
                                    else:    
                                        print("Current Trade realized loss : %.2f\n" % abs(realized_pnl))
                                        send_messages("Current Trade realized loss : %.2f\n" % abs(realized_pnl), get_messages)
                                    
                                    buy_entry=0
                                    sell_entry=0
                                    buy_sl=0
                                    buy_tp=0
                                    trade=0
                            
                                    store_positions(0,0,0,0,0,0,0,0,0)
                                    
                                    if daily_trades >= max_trades and max_trades > 0:
                                        print("Maximum daily trades reached. Stopping Algo")
                                        send_messages("Maximum daily trades reached. Stopping Algo",get_messages)
                                        tm.sleep(15)
                                        sys.exit()
                            
                                if price <= sell_tp:
                                    alice.cancel_order(orderid)
                                    buy_sq_id, buy_exit = place_buy_orders(op,'',option_qty,option_exchange,buffer_pct,roundoff)
                                    
                                    print("\nBuy Target hit at %s"%(buy_exit))
                                    send_messages("\nBuy Target hit at %s"%(buy_exit),get_messages)
                                    #print("Buy Trade Squaredoff at %.2f" % sell_exit)
                                    #send_messages("Buy Trade Squaredoff at %.2f" % sell_exit,get_messages)
                                    
                                    if exch=='MCX':
                                        realized_pnl=(last_buy_price - buy_exit)*option_qty
                                    else:    
                                        realized_pnl=(last_sell_price - buy_exit)*option_qty
                                        
                                    print("Current Trade realized profit : %.2f\n" % abs(realized_pnl))
                                    send_messages("Current Trade realized profit : %.2f\n" % abs(realized_pnl), get_messages)
                                    #daily_pnl.append(realized_pnl)
                                    #net_realized=np.sum(daily_pnl)
                                    #print(f"Daywise realized pnl: {net_realized}\n")
                                    
                                    buy_entry=0
                                    sell_entry=0
                                    sell_sl=0
                                    sell_tp=0
                                    trade=0
                                    
                                    store_positions(0,0,0,0,0,0,0,0,0)
                            
                                    if daily_trades >= max_trades and max_trades > 0:
                                        print("Maximum daily trades reached. Stopping Algo")
                                        send_messages("Maximum daily trades reached. Stopping Algo",get_messages)
                                        tm.sleep(15)
                                        sys.exit()
   # dont till here  -------------------------------------------------------------------                                            
                        elif sltp_inst=='SYMBOL':
                            
                            if price <= buy_sl:
                                
                                print("buy sl hit at %s"%(buy_sl))
                                send_messages("buy sl hit at %s"%(buy_sl),get_messages)
                                buy_sq_id=place_buy_orders(op,'',option_qty,option_exchange,buffer_pct,roundoff)
                                realized_pnl=(float(strike_dict[op_token])-last_buy_price)*option_qty
                                daily_pnl.append(realized_pnl)
                                net_realized=np.sum(daily_pnl)
                                print(f"Daywise realized pnl: {net_realized}\n")
                                print("buy trade squaredoff at %.2f" % price)
                                send_messages("buy trade squaredoff at %.2f" % price,get_messages)
                                buy_entry=0
                                sell_entry=0
                                buy_sl=0
                                buy_tp=0
                                trade=0
                                store_positions(0,0,0,0,0,0,0,0,0)
                                if daily_trades >= max_trades and max_trades > 0:
                                    print("Maximum daily trades reached. Stopping Algo")
                                    send_messages("Maximum daily trades reached. Stopping Algo",get_messages)
                                    tm.sleep(15)
                                    sys.exit()
                            
                                
                            elif price >= buy_tp:
                                
                                print("buy target hit at %s"%(buy_tp))
                                send_messages("buy target hit at %s"%(buy_tp),get_messages)
                                
                                buy_sq_id=place_buy_orders(op,'',option_qty,option_exchange,buffer_pct,roundoff)
                                realized_pnl=(float(strike_dict[op_token])-last_buy_price)*option_qty
                                daily_pnl.append(realized_pnl)
                                net_realized=np.sum(daily_pnl)
                                print(f"Daywise realized pnl: {net_realized}\n")
                                
                                buy_entry=0
                                sell_entry=0
                                buy_sl=0
                                buy_tp=0
                                trade=0
                                store_positions(0,0,0,0,0,0,0,0,0)
                                if daily_trades >= max_trades and max_trades > 0:
                                    print("Maximum daily trades reached. Stopping Algo")
                                    send_messages("Maximum daily trades reached. Stopping Algo",get_messages)
                                    tm.sleep(15)
                                    sys.exit()
                                else:
                                    pass
                            
                            
                            
                    if option_strategy.upper() == "BUY":
                        
                            
                        #if price <= buy_sl:
                            
                            with contextlib.redirect_stdout(None):
                                ord_stat = shoonya.single_order_history(orderid)[0]['status']
                            if ord_stat == 'COMPLETE':
                                    with contextlib.redirect_stdout(None):
                                        buy_exit = float(shoonya.single_order_history(orderno=orderid)[0]['avgprc'])
                                    print("\nBuy SL hit at %.2f"%(buy_exit))
                                    send_messages("\nBuy SL hit at %.2f"%(buy_exit),get_messages)
                                    
                                    if exch=='MCX':
                                        realized_pnl=(last_buy_price - buy_exit)*option_qty
                                    else:    
                                        realized_pnl=(last_buy_price - buy_exit)*option_qty
                                    if realized_pnl < 0:
                                        print("Current Trade realized profit : %.2f\n" % abs(realized_pnl))
                                        send_messages("Current Trade realized profit : %.2f\n" % abs(realized_pnl), get_messages)
                                    else:    
                                        print("Current Trade realized loss : %.2f\n" % abs(realized_pnl))
                                        send_messages("Current Trade realized loss : %.2f\n" % abs(realized_pnl), get_messages)
                                    
                                    #daily_pnl.append(realized_pnl)
                                    #net_realized=np.sum(daily_pnl)
                                    #print(f"Daywise realized pnl: {net_realized}\n")
                                    
                                    buy_entry=0
                                    sell_entry=0
                                    buy_sl=0
                                    buy_tp=0
                                    trade=0
                                    q = option_qty
                                    
                                    store_positions(0,0,0,0,0,0,0,0,0)
                                    save_positions(op_symbol,"SELL",float(buy_exit),q)
                                    
                                    #--------------------------------------------------------------------
                                   
                                    day_NFO_PNL, day_MCX_PNL = Calculate_PNL()
                                    today_pnl = day_NFO_PNL + day_MCX_PNL
                                    
                                    print("Today's NFO PnL: %.2f" % day_NFO_PNL)
                                    print("Today's MCX PnL: %.2f" % day_MCX_PNL)
                                    print("Today's All PnL: %.2f\n" % today_pnl)
                                    
                                    send_messages("Today's NFO PnL: %.2f {% day_NFO998_PNL}",get_messages)
                                    send_messages("Today's MCX PnL: %.2f {% day_MCX_PNL}",get_messages)
                                    send_messages("Today's All PnL: %.2f {% today_pnl}\n",get_messages)
                                    
                                    #--------------------------------------------------------------------
                                    
                                    if daily_trades >= max_trades and max_trades > 0:
                                        print("Maximum daily trades reached. Stopping Algo")
                                        send_messages("Maximum daily trades reached. Stopping Algo",get_messages)
                                        tm.sleep(15)
                                        sys.exit()
                            
                            elif price < buy_sl:   
                                
                                with contextlib.redirect_stdout(None):
                                    shoonya.cancel_order(orderno=orderid)
                                with contextlib.redirect_stdout(None):
                                    sell_sq_id, buy_exit = place_sell_orders(op_symbol,option_qty,option_exchange,buffer_pct,roundoff)
                            
                                print("\nBuy SL hit at %.2f"%(buy_exit))
                                send_messages("\nBuy SL hit at %.2f"%(buy_exit),get_messages)
                                
                                if exch=='MCX':
                                    realized_pnl=(last_buy_price - buy_exit)*option_qty
                                else:    
                                    realized_pnl=(last_buy_price - buy_exit)*option_qty
                                if realized_pnl < 0:
                                    print("Current Trade realized profit : %.2f\n" % abs(realized_pnl))
                                    send_messages("Current Trade realized profit : %.2f\n" % abs(realized_pnl), get_messages)
                                else:    
                                    print("Current Trade realized loss : %.2f\n" % abs(realized_pnl))
                                    send_messages("Current Trade realized loss : %.2f\n" % abs(realized_pnl), get_messages)
                                
                                #--------------------------------------------------------------------
                               
                                day_NFO_PNL, day_MCX_PNL = Calculate_PNL()
                                today_pnl = day_NFO_PNL + day_MCX_PNL
                                
                                print("Today's NFO PnL: %.2f" % day_NFO_PNL)
                                print("Today's MCX PnL: %.2f" % day_MCX_PNL)
                                print("Today's All PnL: %.2f\n" % today_pnl)
                                
                                send_messages("Today's NFO PnL: %.2f {% day_NFO998_PNL}",get_messages)
                                send_messages("Today's MCX PnL: %.2f {% day_MCX_PNL}",get_messages)
                                send_messages("Today's All PnL: %.2f {% today_pnl}\n",get_messages)
                                
                                #--------------------------------------------------------------------
                                
                                #daily_pnl.append(realized_pnl)
                                #net_realized=np.sum(daily_pnl)
                                #print(f"Daywise realized pnl: {net_realized}\n")
                                
                                buy_entry=0
                                sell_entry=0
                                buy_sl=0
                                buy_tp=0
                                trade=0
                                q = option_qty