Starting Live SuperTrend Analysis…
Instrument: NSE_EQ|INE031A01017
Connecting to Upstox WebSocket…
Successfully fetched feed URL
Connected to WebSocket
Subscribed to NSE_EQ|INE031A01017
i am etting this in my code - import asyncio
import websockets
import ssl
import json
from datetime import datetime, timedelta
import pytz
import pandas as pd
import numpy as np
from google.protobuf.json_format import ParseDict
from market_data_feed_pb2 import FeedResponse
import aiohttp
Configuration
API_KEY = “” # Replace with your actual API key
ACCESS_TOKEN = “” # Replace with valid token
INSTRUMENT = “NSE_EQ|INE031A01017” # HUDCO
Rolling price buffer for SuperTrend
price_buffer =
def calculate_supertrend(df, period, multiplier):
df[‘prev_close’] = df[‘close’].shift(1).fillna(df[‘close’])
df[‘tr1’] = df[‘high’] - df[‘low’]
df[‘tr2’] = abs(df[‘high’] - df[‘prev_close’])
df[‘tr3’] = abs(df[‘low’] - df[‘prev_close’])
df[‘tr’] = df[[‘tr1’, ‘tr2’, ‘tr3’]].max(axis=1)
df[‘atr’] = df[‘tr’].rolling(window=period).mean()
hl_avg = (df['high'] + df['low']) / 2
df['upper_band'] = hl_avg + (multiplier * df['atr'])
df['lower_band'] = hl_avg - (multiplier * df['atr'])
df['final_upper_band'] = df['upper_band'].copy()
df['final_lower_band'] = df['lower_band'].copy()
for i in range(1, len(df)):
if df.loc[i, 'upper_band'] < df.loc[i-1, 'final_upper_band'] or df.loc[i-1, 'close'] > df.loc[i-1, 'final_upper_band']:
df.loc[i, 'final_upper_band'] = df.loc[i, 'upper_band']
else:
df.loc[i, 'final_upper_band'] = df.loc[i-1, 'final_upper_band']
if df.loc[i, 'lower_band'] > df.loc[i-1, 'final_lower_band'] or df.loc[i-1, 'close'] < df.loc[i-1, 'final_lower_band']:
df.loc[i, 'final_lower_band'] = df.loc[i, 'lower_band']
else:
df.loc[i, 'final_lower_band'] = df.loc[i-1, 'final_lower_band']
df['supertrend'] = np.nan
df['trend'] = 1
df.loc[0, 'supertrend'] = df.loc[0, 'final_lower_band']
df.loc[0, 'trend'] = 1
for i in range(1, len(df)):
if df.loc[i-1, 'trend'] == 1:
if df.loc[i, 'close'] < df.loc[i, 'final_lower_band']:
df.loc[i, 'supertrend'] = df.loc[i, 'final_upper_band']
df.loc[i, 'trend'] = -1
else:
df.loc[i, 'supertrend'] = df.loc[i, 'final_lower_band']
df.loc[i, 'trend'] = 1
else:
if df.loc[i, 'close'] > df.loc[i, 'final_upper_band']:
df.loc[i, 'supertrend'] = df.loc[i, 'final_lower_band']
df.loc[i, 'trend'] = 1
else:
df.loc[i, 'supertrend'] = df.loc[i, 'final_upper_band']
df.loc[i, 'trend'] = -1
return df.iloc[-1]
def analyze_market(current_price):
global price_buffer
now = datetime.now(pytz.UTC)
# Add new price to rolling buffer
price_buffer.append({
'timestamp': now,
'open': current_price,
'high': current_price,
'low': current_price,
'close': current_price
})
# Keep only last 50 prices
if len(price_buffer) > 50:
price_buffer.pop(0)
if len(price_buffer) < 20:
return None
df = pd.DataFrame(price_buffer)
st1 = calculate_supertrend(df.copy(), period=6, multiplier=1.1)
st2 = calculate_supertrend(df.copy(), period=12, multiplier=2.2)
support_levels = []
resistance_levels = []
if st1['trend'] == 1:
support_levels.append(st1['supertrend'])
else:
resistance_levels.append(st1['supertrend'])
if st2['trend'] == 1:
support_levels.append(st2['supertrend'])
else:
resistance_levels.append(st2['supertrend'])
support = max(support_levels) if support_levels else df['low'].tail(10).min()
resistance = min(resistance_levels) if resistance_levels else df['high'].tail(10).max()
trend_summary = ""
if st1['trend'] == 1 and st2['trend'] == 1:
trend_summary = "STRONG UPTREND"
elif st1['trend'] == -1 and st2['trend'] == -1:
trend_summary = "STRONG DOWNTREND"
else:
trend_summary = "MIXED TREND"
return {
'current_price': current_price,
'support': support,
'resistance': resistance,
'st1_value': st1['supertrend'],
'st2_value': st2['supertrend'],
'st1_trend': 'UPTREND' if st1['trend'] == 1 else 'DOWNTREND',
'st2_trend': 'UPTREND' if st2['trend'] == 1 else 'DOWNTREND',
'trend_summary': trend_summary
}
def format_analysis(analysis):
“”“Format analysis results for display”“”
output = “\n” + “=”*60
output += “\n📊 LIVE SUPERTREND LEVELS”
output += “\n” + “=”*60
output += f"\n💰 Current Price : ₹{analysis[‘current_price’]/100:.2f}"
output += f"\n🔻 Support Level : ₹{analysis[‘support’]/100:.2f}"
output += f"\n🔺 Resistance Level : ₹{analysis[‘resistance’]/100:.2f}"
output += “\n\n📊 SUPERTREND INDICATORS”
output += “\n” + “-”*25
output += f"\n📈 SuperTrend 6-1.1 : ₹{analysis[‘st1_value’]/100:.2f} ({analysis[‘st1_trend’]})"
output += f"\n📈 SuperTrend 12-2.2 : ₹{analysis[‘st2_value’]/100:.2f} ({analysis[‘st2_trend’]})"
output += f"\n📊 Overall Trend : {analysis[‘trend_summary’]}"
output += “\n” + “=”*60
return output
async def get_websocket_feed_url():
url = “https://api.upstox.com/v2/feed/market-data-feed/authorize”
headers = {“Authorization”: f"Bearer {ACCESS_TOKEN}"}
async with aiohttp.ClientSession() as session:
async with session.get(url, headers=headers) as response:
if response.status == 200:
data = await response.json()
if data.get("status") == "success" and data.get("data", {}).get("authorizedRedirectUri"):
print("🟢 Successfully fetched feed URL")
return data["data"]["authorizedRedirectUri"]
print(f"❌ Failed to fetch feed URL. Status code: {response.status}")
return None
async def connect_to_websocket():
feed_url = await get_websocket_feed_url()
if not feed_url:
print(“ Cannot proceed without valid feed URL”)
return
ssl_context = ssl._create_unverified_context()
async with websockets.connect(feed_url, ssl=ssl_context) as websocket:
print("🟢 Connected to WebSocket")
# Subscribe to LTPC
subscribe_message = {
"guid": "unique_request_id",
"method": "sub",
"data": {
"mode": "ltpc",
"instrumentKeys": [INSTRUMENT]
}
}
await websocket.send(json.dumps(subscribe_message))
print(f"🔔 Subscribed to {INSTRUMENT}")
while True:
try:
message = await websocket.recv()
if isinstance(message, str):
continue # Skip text messages
# Deserialize Protobuf binary message
feed_response = FeedResponse()
feed_response.ParseFromString(message)
# Convert to JSON/dict
response_dict = ParseDict(json.loads(feed_response.toJson()), FeedResponse())
# Process live data
process_live_data(response_dict)
except Exception as e:
print(f"⚠️ Error receiving message: {str(e)}")
def process_live_data(data):
global price_buffer
if hasattr(data, 'feeds'):
for key, value in data.feeds.items():
if key == INSTRUMENT:
ltp = None
if hasattr(value, 'ltpc'):
ltp = value.ltpc.ltp
elif hasattr(value, 'depth') and len(value.depth.buy) > 0:
ltp = value.depth.buy[0].price
if ltp:
print(f"📥 Tick received: ₹{ltp / 100:.2f}") # Show price immediately
analysis = analyze_market(ltp)
if analysis:
print(format_analysis(analysis))
async def main():
print(“ Starting Live SuperTrend Analysis…”)
print(“=”*55)
print(f" Instrument: {INSTRUMENT}")
print(“ Connecting to Upstox WebSocket…”)
while True:
try:
await connect_to_websocket()
except Exception as e:
print(f"⚠️ Connection error: {str(e)}")
print("🔄 Reconnecting in 5 seconds...")
await asyncio.sleep(5)
if name == “main”:
asyncio.run(main())