Path: blob/main/SmartApi/smartWebSocketOrderUpdate.py
410 views
import ssl1import websocket2import time3import logging4from logzero import logger5import logzero6import os78class SmartWebSocketOrderUpdate(object):9WEBSOCKET_URI = "wss://tns.angelone.in/smart-order-update"10HEARTBEAT_MESSAGE = "ping" # Heartbeat message to maintain Socket connection.11HEARTBEAT_INTERVAL_SECONDS = 10 # Interval for sending heartbeat messages to keep the connection alive.12MAX_CONNECTION_RETRY_ATTEMPTS = 2 # Max retry attempts to establish Socket connection in case of failure.13RETRY_DELAY_SECONDS = 10 # Delay between retry attempts when reconnecting to Socket in case of failure.14wsapp = None #Socket connection instance15last_pong_timestamp = None #Timestamp of the last received pong message16current_retry_attempt = 0 #Current retry attempt count1718def __init__(self, auth_token, api_key, client_code, feed_token):19self.auth_token = auth_token20self.api_key = api_key21self.client_code = client_code22self.feed_token = feed_token23# Create a log folder based on the current date24log_folder = time.strftime("%Y-%m-%d", time.localtime())25log_folder_path = os.path.join("logs", log_folder) # Construct the full path to the log folder26os.makedirs(log_folder_path, exist_ok=True) # Create the log folder if it doesn't exist27log_path = os.path.join(log_folder_path, "app.log") # Construct the full path to the log file28logzero.logfile(log_path, loglevel=logging.INFO) # Output logs to a date-wise log file2930def on_message(self, wsapp, message):31logger.info("Received message: %s", message)3233def on_data(self, wsapp, message, data_type, continue_flag):34self.on_message(wsapp, message)3536def on_open(self, wsapp):37logger.info("Connection opened")3839def on_error(self, wsapp, error):40logger.error("Error: %s", error)4142def on_close(self, wsapp, close_status_code, close_msg):43logger.info("Connection closed")44self.retry_connect()4546def on_ping(self, wsapp, data):47timestamp = time.time()48formatted_timestamp = time.strftime("%d-%m-%y %H:%M:%S", time.localtime(timestamp))49logger.info("In on ping function ==> %s, Timestamp: %s", data, formatted_timestamp)5051def on_pong(self, wsapp, data):52if data == self.HEARTBEAT_MESSAGE:53timestamp = time.time()54formatted_timestamp = time.strftime("%d-%m-%y %H:%M:%S", time.localtime(timestamp))55logger.info("In on pong function ==> %s, Timestamp: %s", data, formatted_timestamp)56self.last_pong_timestamp = timestamp57else:58self.on_data(wsapp, data, websocket.ABNF.OPCODE_BINARY, False)5960def check_connection_status(self):61current_time = time.time()62if self.last_pong_timestamp is not None and current_time - self.last_pong_timestamp > 2 * self.HEARTBEAT_INTERVAL_SECONDS:63self.close_connection()6465def connect(self):66headers = {67"Authorization": self.auth_token,68"x-api-key": self.api_key,69"x-client-code": self.client_code,70"x-feed-token": self.feed_token71}72try:73self.wsapp = websocket.WebSocketApp(self.WEBSOCKET_URI, header=headers, on_open=self.on_open,74on_error=self.on_error, on_close=self.on_close,75on_data=self.on_data, on_ping=self.on_ping, on_pong=self.on_pong)76self.wsapp.run_forever(sslopt={"cert_reqs": ssl.CERT_NONE}, ping_interval=self.HEARTBEAT_INTERVAL_SECONDS)77except Exception as e:78logger.error("Error connecting to WebSocket: %s", e)79self.retry_connect()8081def retry_connect(self):82if self.current_retry_attempt < self.MAX_CONNECTION_RETRY_ATTEMPTS:83logger.info("Retrying connection (Attempt %s)...", self.current_retry_attempt + 1)84time.sleep(self.RETRY_DELAY_SECONDS)85self.current_retry_attempt += 186self.connect()87else:88logger.warning("Max retry attempts reached.")8990def close_connection(self):91if self.wsapp:92self.wsapp.close()939495