File size: 3,668 Bytes
d11c4bf
 
 
d33f2ad
d11c4bf
 
 
 
 
 
 
 
 
 
 
 
d33f2ad
d11c4bf
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
# @title TOKEN GENERATER FOR NF,BN,FN

import gradio as gr
#import pyotp
from api_helper import ShoonyaApiPy
import threading
import time
import traceback
from datetime import datetime, timedelta

# Initialize API
api = ShoonyaApiPy()

# Credentials
user = 'FA28777'
pwd = 'Ebgc@D55'
factor2 = ''      #pyotp.TOTP('445KIV2355QM5266QJ557MA55P77V763').now()
vc = 'FA28777_U'
app_key = 'd23f2af8135baf5a67ec90cd2d8c6ebf'
imei = 'abc1234'

try:
    print("Attempting to log in...")
    ret = api.login(userid=user, password=pwd, twoFA=factor2, vendor_code=vc, api_secret=app_key, imei=imei)
    print(f"Login response: {ret}")
except Exception as e:
    print(f"An error occurred during login: {str(e)}")
    traceback.print_exc()

def get_next_expiry(index_name):
    today = datetime.now()
    weekday = today.weekday()

    if index_name == "NIFTY":
        expiry_day = 3  # Thursday
    elif index_name == "BANKNIFTY":
        expiry_day = 2  # Wednesday
    elif index_name == "FINNIFTY":
        expiry_day = 1  # Tuesday
    else:
        return None

    # Get the nearest expiry date
    days_until_expiry = (expiry_day - weekday) % 7
    expiry_date = today + timedelta(days=days_until_expiry)

    # FINNIFTY uses a different format for expiry as per the example you provided
    if index_name == "FINNIFTY":
        return expiry_date.strftime('%d%b%y').upper()  # Example: 10SEP24
    else:
        return expiry_date.strftime('%d%b%y').upper()  # Example: 05SEP24

def fetch_option_tokens(index_name, strike_price):
    try:
        expiry_date = get_next_expiry(index_name.upper())
        if not expiry_date:
            return f"Invalid index name: {index_name}"

        # Define strike interval
        if index_name.upper() == "NIFTY" or index_name.upper() == "FINNIFTY":
            strike_interval = 50
        elif index_name.upper() == "BANKNIFTY":
            strike_interval = 100
        else:
            return "Invalid index. Supported: NIFTY, BANKNIFTY, FINNIFTY."

        # Round strike price to nearest interval
        nearest_strike = round(strike_price / strike_interval) * strike_interval

        # Construct the query with a space between the index name, expiry, and strike price
        ce_query = f"{index_name.upper()}{expiry_date}C{int(nearest_strike)}"
        pe_query = f"{index_name.upper()}{expiry_date}P{int(nearest_strike)}"

        print(f"CE query: {ce_query}")
        print(f"PE query: {pe_query}")

        ce_response = api.searchscrip('NFO', ce_query)
        pe_response = api.searchscrip('NFO', pe_query)

        ce_token = ce_response['values'][0]['token'] if ce_response and 'values' in ce_response else "Not Found"
        pe_token = pe_response['values'][0]['token'] if pe_response and 'values' in pe_response else "Not Found"

        print(f"CE token: {ce_token}")
        print(f"PE token: {pe_token}")

        return f"CE Token: {ce_token}\nPE Token: {pe_token}"

    except Exception as e:
        print(f"An error occurred in fetch_option_tokens: {str(e)}")
        traceback.print_exc()
        return "Error: No response from API."

with gr.Blocks() as demo:
    index_name = gr.Textbox(label="Index Name", value="NIFTY")
    strike_price = gr.Number(label="Strike Price", value=25200)
    output = gr.Textbox(label="Tokens", interactive=False)
    status = gr.Textbox(label="Status", interactive=False)

    def update_status(index_name, strike_price):
        status_text = fetch_option_tokens(index_name, strike_price)
        return status_text

    button = gr.Button("Get Tokens")
    button.click(update_status, inputs=[index_name, strike_price], outputs=[output])

demo.launch(share=True)