Activegg commited on
Commit
2856382
·
verified ·
1 Parent(s): b61da77

Update app.py

Browse files
Files changed (1) hide show
  1. app.py +7 -269
app.py CHANGED
@@ -1,273 +1,11 @@
1
- # @title CLAUDE GENRTD CODE FOR AUTOMATIC STRIKE CHANGES AND CP ChHANGES for MCX CRUDEOILM
2
-
3
  import gradio as gr
4
- import pyotp
5
- from api_helper import ShoonyaApiPy
6
- import threading
7
- import time
8
- from collections import deque
9
- import pandas as pd
10
- import plotly.graph_objects as go
11
- import traceback
12
- import asyncio
13
- import datetime
14
-
15
- # Global variables
16
- crudeoilm_ltp = None
17
- ce_ltp = None
18
- pe_ltp = None
19
- current_strike = None
20
- strike_interval = 50 # Adjust if CRUDEOILM has a different strike interval
21
- ce_token = None
22
- pe_token = None
23
-
24
- # Initialize lock for thread safety
25
- data_lock = threading.Lock()
26
-
27
- # Deque to store historical data for the chart
28
- MAX_POINTS = 500
29
- historical_data = deque(maxlen=MAX_POINTS)
30
-
31
- # Event to signal when we're connected and subscribed
32
- api_ready = threading.Event()
33
-
34
- # Create a global FigureWidget for the Plotly chart
35
- fig_widget = go.FigureWidget()
36
-
37
- # New global variable to store the latest data
38
- latest_data = {"premium": None, "time": None, "strike": None}
39
-
40
- # Global API instance
41
- api = ShoonyaApiPy()
42
-
43
- # CRUDEOILM expiry dates
44
- expiry_dates = [
45
- datetime.datetime.strptime("17/09/24", "%d/%m/%y").date(),
46
- datetime.datetime.strptime("17/10/24", "%d/%m/%y").date(),
47
- datetime.datetime.strptime("15/11/24", "%d/%m/%y").date(),
48
- datetime.datetime.strptime("16/12/24", "%d/%m/%y").date()
49
- ]
50
-
51
- def run_api():
52
- global crudeoilm_ltp, ce_ltp, pe_ltp, current_strike, ce_token, pe_token
53
-
54
- # Credentials
55
- user = 'FA28777'
56
- pwd = 'Ebgc@D55'
57
- factor2 = pyotp.TOTP('445KIV2355QM5266QJ557MA55P77V763').now()
58
- vc = 'FA28777_U'
59
- app_key = 'd23f2af8135baf5a67ec90cd2d8c6ebf'
60
- imei = 'abc1234'
61
-
62
- try:
63
- print("Attempting to log in...")
64
- ret = api.login(userid=user, password=pwd, twoFA=factor2, vendor_code=vc, api_secret=app_key, imei=imei)
65
- print(f"Login response: {ret}")
66
-
67
- if 'stat' not in ret or ret['stat'] != 'Ok':
68
- print(f"Login failed. Response: {ret}")
69
- return
70
-
71
- def event_handler_feed_update(tick_data):
72
- global crudeoilm_ltp, ce_ltp, pe_ltp, current_strike, ce_token, pe_token
73
- print(f"Received tick data: {tick_data}")
74
-
75
- if 'lp' in tick_data and 'tk' in tick_data:
76
- token = tick_data['tk']
77
- ltp = float(tick_data['lp'])
78
-
79
- with data_lock:
80
- if token == get_crudeoilm_token():
81
- crudeoilm_ltp = ltp
82
- new_strike = get_atm_strike(crudeoilm_ltp)
83
- if new_strike != current_strike:
84
- update_subscriptions(api, current_strike, new_strike)
85
- current_strike = new_strike
86
- elif token == ce_token:
87
- ce_ltp = ltp
88
- elif token == pe_token:
89
- pe_ltp = ltp
90
-
91
- def open_callback():
92
- print("WebSocket connection opened.")
93
- api_ready.set()
94
-
95
- api.start_websocket(order_update_callback=lambda x: None,
96
- subscribe_callback=event_handler_feed_update,
97
- socket_open_callback=open_callback)
98
-
99
- print("Subscribing to CRUDEOILM...")
100
- api.subscribe([f"MCX|{get_crudeoilm_token()}"])
101
- print("Subscribed to CRUDEOILM.")
102
-
103
- while True:
104
- time.sleep(1)
105
- except Exception as e:
106
- print(f"An error occurred in run_api: {str(e)}")
107
- traceback.print_exc()
108
-
109
- def get_crudeoilm_token():
110
- # Replace with actual CRUDEOILM token
111
- return "430107" # This is a placeholder, replace with the correct token
112
-
113
- def get_atm_strike(crudeoilm_value):
114
- return round(crudeoilm_value / strike_interval) * strike_interval
115
-
116
- def get_option_tokens(strike):
117
- global ce_token, pe_token
118
- expiry_date = get_next_expiry()
119
- ce_symbol = f"CRUDEOILM{expiry_date}C{strike}"
120
- pe_symbol = f"CRUDEOILM{expiry_date}P{strike}"
121
-
122
- ce_result = api.searchscrip('MCX', ce_symbol)
123
- pe_result = api.searchscrip('MCX', pe_symbol)
124
-
125
- if ce_result['stat'] == 'Ok' and pe_result['stat'] == 'Ok':
126
- ce_token = ce_result['values'][0]['token']
127
- pe_token = pe_result['values'][0]['token']
128
- print(f"Fetched tokens - CE: {ce_token}, PE: {pe_token}")
129
- return ce_token, pe_token
130
- else:
131
- print(f"Error fetching tokens for strike {strike}")
132
- return None, None
133
-
134
- def get_next_expiry():
135
- today = datetime.date.today()
136
- next_expiry = min(date for date in expiry_dates if date >= today)
137
- return next_expiry.strftime("%d%b%y").upper()
138
-
139
- def update_subscriptions(api, old_strike, new_strike):
140
- global ce_token, pe_token
141
- if old_strike:
142
- api.unsubscribe([f"MCX|{ce_token}", f"MCX|{pe_token}"])
143
- ce_token, pe_token = get_option_tokens(new_strike)
144
- if ce_token and pe_token:
145
- api.subscribe([f"MCX|{ce_token}", f"MCX|{pe_token}"])
146
-
147
- def get_combined_premium():
148
- if not api_ready.is_set():
149
- return "Waiting for API connection..."
150
- with data_lock:
151
- if ce_ltp is not None and pe_ltp is not None and current_strike is not None:
152
- combined_premium = ce_ltp + pe_ltp
153
- current_time = pd.Timestamp.now(tz='Asia/Kolkata')
154
- historical_data.append({"time": current_time, "premium": combined_premium, "strike": current_strike})
155
- return f"CRUDEOILM: {crudeoilm_ltp:.2f} | Strike: {current_strike} | Combined Premium: {combined_premium:.2f}"
156
- else:
157
- return f"Waiting for LTP updates... CRUDEOILM: {crudeoilm_ltp}, CE: {ce_ltp}, PE: {pe_ltp}, Strike: {current_strike}"
158
-
159
- def create_chart():
160
- df = pd.DataFrame(list(historical_data))
161
- if df.empty:
162
- fig_widget.data = []
163
- return fig_widget
164
-
165
- x_range = fig_widget.layout.xaxis.range if fig_widget.layout.xaxis.range else None
166
- y_range = fig_widget.layout.yaxis.range if fig_widget.layout.yaxis.range else None
167
-
168
- with fig_widget.batch_update():
169
- fig_widget.data = []
170
- fig_widget.layout.annotations = []
171
-
172
- fig_widget.add_trace(go.Scatter(x=df['time'], y=df['premium'], mode='lines', name='Premium', line=dict(color='orange')))
173
-
174
- fig_widget.update_layout(
175
- title=f"CRUDEOILM ATM Premiums (Current Strike: {current_strike})",
176
- height=500,
177
- margin=dict(l=50, r=50, t=50, b=50),
178
- xaxis_title="Time",
179
- yaxis_title="Net Premium",
180
- template="plotly_dark",
181
- xaxis=dict(
182
- rangeselector=dict(
183
- buttons=list([
184
- dict(count=1, label="1m", step="minute", stepmode="backward"),
185
- dict(count=10, label="10m", step="minute", stepmode="backward"),
186
- dict(count=30, label="30m", step="minute", stepmode="backward"),
187
- dict(count=1, label="1h", step="hour", stepmode="backward"),
188
- dict(step="all")
189
- ]),
190
- font=dict(color="orange"),
191
- bgcolor="black"
192
- ),
193
- rangeslider=dict(visible=True),
194
- type="date",
195
- range=x_range,
196
- tickformat='%H:%M:%S',
197
- tickmode="auto",
198
- showgrid=False
199
- ),
200
- yaxis=dict(range=y_range, showgrid=False),
201
- )
202
-
203
- if not df.empty:
204
- current_premium = df['premium'].iloc[-1]
205
- current_time = df['time'].iloc[-1]
206
- fig_widget.add_annotation(
207
- x=current_time,
208
- y=current_premium,
209
- text=f"{current_premium:.2f}",
210
- showarrow=True,
211
- arrowhead=1,
212
- ax=20,
213
- ay=-40,
214
- font=dict(size=12, color="orange"),
215
- bgcolor="black",
216
- bordercolor="orange",
217
- borderwidth=1
218
- )
219
-
220
- return fig_widget
221
-
222
- async def continuous_data_update():
223
- global latest_data
224
- while True:
225
- premium_info = get_combined_premium()
226
- if "Combined Premium:" in premium_info:
227
- crudeoilm, strike, premium = premium_info.split("|")
228
- crudeoilm_value = float(crudeoilm.split(":")[1].strip())
229
- strike_value = int(strike.split(":")[1].strip())
230
- premium_value = float(premium.split(":")[1].strip())
231
- latest_data = {
232
- "premium": premium_value,
233
- "time": pd.Timestamp.now(tz='Asia/Kolkata'),
234
- "strike": strike_value,
235
- "crudeoilm": crudeoilm_value
236
- }
237
- await asyncio.sleep(1)
238
-
239
- def update_chart():
240
- global historical_data, latest_data
241
- if latest_data["premium"] is not None:
242
- historical_data.append(latest_data)
243
- return create_chart()
244
-
245
- # Start the API thread
246
- thread = threading.Thread(target=run_api, daemon=True)
247
- thread.start()
248
-
249
- # Create Gradio interface
250
- with gr.Blocks(css=".gradio-container {background-color: black; color: white;}") as demo:
251
- gr.Markdown("# CRUDEOILM ATM Premiums Tracker", elem_id="premium-header")
252
- crudeoilm_display = gr.Textbox(label="Current CRUDEOILM Value", elem_id="crudeoilm-display")
253
- strike_display = gr.Textbox(label="Current ATM Strike", elem_id="strike-display")
254
- output = gr.Textbox(label="Current Premium", elem_id="premium-display")
255
- chart = gr.Plot(label="Premium Chart", value=fig_widget)
256
-
257
- async def update_data():
258
- premium_info = get_combined_premium()
259
- crudeoilm_value = latest_data.get("crudeoilm", "N/A")
260
- strike_value = latest_data.get("strike", "N/A")
261
- fig = update_chart()
262
- return f"{crudeoilm_value:.2f}" if isinstance(crudeoilm_value, float) else crudeoilm_value, \
263
- str(strike_value), \
264
- premium_info, \
265
- fig
266
 
267
- demo.load(update_data, outputs=[crudeoilm_display, strike_display, output, chart], every=1)
 
268
 
269
- # Start the continuous update in the background
270
- asyncio.create_task(continuous_data_update())
 
 
271
 
272
- # Launch Gradio app
273
- demo.queue().launch(share=True)
 
 
 
1
  import gradio as gr
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
2
 
3
+ def dummy_function():
4
+ return "Hello, World!"
5
 
6
+ with gr.Blocks() as demo:
7
+ gr.Markdown("# Test App")
8
+ output = gr.Textbox(label="Output")
9
+ demo.load(dummy_function, outputs=[output])
10
 
11
+ demo.launch()