File size: 10,273 Bytes
5c24304
203a661
 
 
 
 
 
 
 
 
 
5c24304
203a661
 
 
 
 
 
 
 
5c24304
203a661
 
5c24304
203a661
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
6af28cf
 
203a661
 
 
6af28cf
203a661
 
 
 
 
6af28cf
203a661
 
 
 
 
 
6af28cf
 
203a661
 
6af28cf
 
 
 
 
 
 
 
203a661
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
e92a9de
203a661
 
 
 
 
 
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
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
import gradio as gr
import pyotp
from api_helper import ShoonyaApiPy
import threading
import time
from collections import deque
import pandas as pd
import plotly.graph_objects as go
import traceback
import asyncio
import datetime

# Global variables
crudeoilm_ltp = None
ce_ltp = None
pe_ltp = None
current_strike = None
strike_interval = 50  # Adjust if CRUDEOILM has a different strike interval
ce_token = None
pe_token = None

# Initialize lock for thread safety
data_lock = threading.Lock()

# Deque to store historical data for the chart
MAX_POINTS = 500
historical_data = deque(maxlen=MAX_POINTS)

# Event to signal when we're connected and subscribed
api_ready = threading.Event()

# Create a global FigureWidget for the Plotly chart
fig_widget = go.FigureWidget()

# New global variable to store the latest data
latest_data = {"premium": None, "time": None, "strike": None}

# Global API instance
api = ShoonyaApiPy()

# CRUDEOILM expiry dates
expiry_dates = [
    datetime.datetime.strptime("17/09/24", "%d/%m/%y").date(),
    datetime.datetime.strptime("17/10/24", "%d/%m/%y").date(),
    datetime.datetime.strptime("15/11/24", "%d/%m/%y").date(),
    datetime.datetime.strptime("16/12/24", "%d/%m/%y").date()
]

def run_api():
    global crudeoilm_ltp, ce_ltp, pe_ltp, current_strike, ce_token, pe_token

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

        if 'stat' not in ret or ret['stat'] != 'Ok':
            print(f"Login failed. Response: {ret}")
            return

        def event_handler_feed_update(tick_data):
            global crudeoilm_ltp, ce_ltp, pe_ltp, current_strike, ce_token, pe_token
            print(f"Received tick data: {tick_data}")

            if 'lp' in tick_data and 'tk' in tick_data:
                token = tick_data['tk']
                ltp = float(tick_data['lp'])

                with data_lock:
                    if token == get_crudeoilm_token():
                        crudeoilm_ltp = ltp
                        new_strike = get_atm_strike(crudeoilm_ltp)
                        if new_strike != current_strike:
                            update_subscriptions(api, current_strike, new_strike)
                            current_strike = new_strike
                    elif token == ce_token:
                        ce_ltp = ltp
                    elif token == pe_token:
                        pe_ltp = ltp

        def open_callback():
            print("WebSocket connection opened.")
            api_ready.set()

        api.start_websocket(order_update_callback=lambda x: None,
                            subscribe_callback=event_handler_feed_update,
                            socket_open_callback=open_callback)

        print("Subscribing to CRUDEOILM...")
        api.subscribe([f"MCX|{get_crudeoilm_token()}"])
        print("Subscribed to CRUDEOILM.")

        while True:
            time.sleep(1)
    except Exception as e:
        print(f"An error occurred in run_api: {str(e)}")
        traceback.print_exc()

def get_crudeoilm_token():
    # Replace with actual CRUDEOILM token
    return "430107"  # This is a placeholder, replace with the correct token

def get_atm_strike(crudeoilm_value):
    return round(crudeoilm_value / strike_interval) * strike_interval

def get_option_tokens(strike):
    global ce_token, pe_token
    expiry_date = get_next_expiry()
    ce_symbol = f"CRUDEOILM{expiry_date}C{strike}"
    pe_symbol = f"CRUDEOILM{expiry_date}P{strike}"
    
    ce_result = api.searchscrip('MCX', ce_symbol)
    pe_result = api.searchscrip('MCX', pe_symbol)
    
    if ce_result['stat'] == 'Ok' and pe_result['stat'] == 'Ok':
        ce_token = ce_result['values'][0]['token']
        pe_token = pe_result['values'][0]['token']
        print(f"Fetched tokens - CE: {ce_token}, PE: {pe_token}")
        return ce_token, pe_token
    else:
        print(f"Error fetching tokens for strike {strike}")
        return None, None

def get_next_expiry():
    today = datetime.date.today()
    next_expiry = min(date for date in expiry_dates if date >= today)
    return next_expiry.strftime("%d%b%y").upper()

def update_subscriptions(api, old_strike, new_strike):
    global ce_token, pe_token
    if old_strike:
        api.unsubscribe([f"MCX|{ce_token}", f"MCX|{pe_token}"])
    ce_token, pe_token = get_option_tokens(new_strike)
    if ce_token and pe_token:
        api.subscribe([f"MCX|{ce_token}", f"MCX|{pe_token}"])

def get_combined_premium():
    if not api_ready.is_set():
        return "Waiting for API connection..."
    with data_lock:
        if ce_ltp is not None and pe_ltp is not None and current_strike is not None:
            combined_premium = ce_ltp + pe_ltp
            current_time = pd.Timestamp.now(tz='Asia/Kolkata')
            historical_data.append({"time": current_time, "premium": combined_premium, "strike": current_strike})
            return f"CRUDEOILM: {crudeoilm_ltp:.2f} | Strike: {current_strike} | Combined Premium: {combined_premium:.2f}"
        else:
            return f"Waiting for LTP updates... CRUDEOILM: {crudeoilm_ltp}, CE: {ce_ltp}, PE: {pe_ltp}, Strike: {current_strike}"

def create_chart():
    df = pd.DataFrame(list(historical_data))
    if df.empty:
        fig_widget.data = []
        return fig_widget

    x_range = fig_widget.layout.xaxis.range if fig_widget.layout.xaxis.range else None
    y_range = fig_widget.layout.yaxis.range if fig_widget.layout.yaxis.range else None

    with fig_widget.batch_update():
        fig_widget.data = []
        fig_widget.layout.annotations = []

        fig_widget.add_trace(go.Scatter(x=df['time'], y=df['premium'], mode='lines', name='Premium', line=dict(color='orange')))

        fig_widget.update_layout(
            title=f"CRUDEOILM ATM Premiums (Current Strike: {current_strike})",
            height=500,
            margin=dict(l=50, r=50, t=50, b=50),
            xaxis_title="Time",
            yaxis_title="Net Premium",
            template="plotly_dark",
            xaxis=dict(
                rangeselector=dict(
                    buttons=list([
                        dict(count=1, label="1m", step="minute", stepmode="backward"),
                        dict(count=10, label="10m", step="minute", stepmode="backward"),
                        dict(count=30, label="30m", step="minute", stepmode="backward"),
                        dict(count=1, label="1h", step="hour", stepmode="backward"),
                        dict(step="all")
                    ]),
                    font=dict(color="orange"),
                    bgcolor="black"
                ),
                rangeslider=dict(visible=True),
                type="date",
                range=x_range,
                tickformat='%H:%M:%S',
                tickmode="auto",
                showgrid=False
            ),
            yaxis=dict(range=y_range, showgrid=False),
        )

        if not df.empty:
            current_premium = df['premium'].iloc[-1]
            current_time = df['time'].iloc[-1]
            fig_widget.add_annotation(
                x=current_time,
                y=current_premium,
                text=f"{current_premium:.2f}",
                showarrow=True,
                arrowhead=1,
                ax=20,
                ay=-40,
                font=dict(size=12, color="orange"),
                bgcolor="black",
                bordercolor="orange",
                borderwidth=1
            )

    return fig_widget

latest_data = {}

async def continuous_data_update():
    global latest_data
    while True:
        premium_info = get_combined_premium()  # Make sure this function works synchronously
        if "Combined Premium:" in premium_info:
            crudeoilm, strike, premium = premium_info.split("|")
            crudeoilm_value = float(crudeoilm.split(":")[1].strip())
            strike_value = int(strike.split(":")[1].strip())
            premium_value = float(premium.split(":")[1].strip())
            
            latest_data = {
                "premium": premium_value,
                "time": pd.Timestamp.now(tz='Asia/Kolkata'),
                "strike": strike_value,
                "crudeoilm": crudeoilm_value
            }
        
        # Sleep for 1 second between updates
        await asyncio.sleep(1)

async def main():
    # Run the data update task
    await continuous_data_update()

if __name__ == "__main__":
    # Start the event loop and run the main coroutine
    asyncio.run(main())

def update_chart():
    global historical_data, latest_data
    if latest_data["premium"] is not None:
        historical_data.append(latest_data)
    return create_chart()

# Start the API thread
thread = threading.Thread(target=run_api, daemon=True)
thread.start()

# Create Gradio interface
with gr.Blocks(css=".gradio-container {background-color: black; color: white;}") as demo:
    gr.Markdown("# CRUDEOILM ATM Premiums Tracker", elem_id="premium-header")
    crudeoilm_display = gr.Textbox(label="Current CRUDEOILM Value", elem_id="crudeoilm-display")
    strike_display = gr.Textbox(label="Current ATM Strike", elem_id="strike-display")
    output = gr.Textbox(label="Current Premium", elem_id="premium-display")
    chart = gr.Plot(label="Premium Chart", value=fig_widget)

    async def update_data():
        premium_info = get_combined_premium()
        crudeoilm_value = latest_data.get("crudeoilm", "N/A")
        strike_value = latest_data.get("strike", "N/A")
        fig = update_chart()
        return f"{crudeoilm_value:.2f}" if isinstance(crudeoilm_value, float) else crudeoilm_value, \
               str(strike_value), \
               premium_info, \
               fig

    demo.load(update_data, outputs=[crudeoilm_display, strike_display, output, chart], every=60)

# Start the continuous update in the background
asyncio.create_task(continuous_data_update())

# Launch Gradio app
demo.queue().launch(share=True)