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