Web Socket Not Streaming


  • -- coding: utf-8 --

    """
    Created on Wed Nov 8 14:18:05 2023

    @author: sspra
    """

    Importing Libraries

    from SmartApi import SmartConnect
    from SmartApi.smartWebSocketV2 import SmartWebSocketV2
    from logzero import logger
    import os
    working_dir = os.chdir("D:\Angel Broking Kosal")
    import datetime as dt
    import pyotp
    import kosalauth
    import urllib
    import json
    import pandas as pd
    import pandas_ta as indi
    import ta
    import schedule
    import time
    import numpy as np
    import threading
    import pytz
    import requests
    import gspread
    UTC = pytz.timezone('Asia/Kolkata')

    User Inputs

    START_TIME = [10,7,0] # Algo Start Time
    EXIT_TIME = [10,10,0] # Algo End Time
    Fresh_Buy_Entry_TP = 0.03
    Fresh_sell_Entry_TP = 0.03
    Buy_Continue_TP = 0.03
    Sell_Continue_TP = 0.03
    profit_dist = 1.0025
    lot = 1
    Stop_Loss = 0.02

    List of stocks to Trade

    Ticker = ["WIPRO","EICHERMOT","HAVELLS","APOLLOHOSP","ASIANPAINT","ICICIBANK","TECHM","HINDUNILVR","BAJAJFINSV","HEROMOTOCO","INDUSINDBK","SBIN","SUNPHARMA","TVSMOTOR"]

    #Ticker = ["KOTAKBANK"]

    Angel Api Login

    smartApi = SmartConnect(kosalauth.apikey)
    data = smartApi.generateSession(kosalauth.clientId, kosalauth.pin, pyotp.TOTP(kosalauth.token).now())

    Download Scrip Master File

    def download_token_list_csv():

    # getting instrument Token
    instrument_url = "https://margincalculator.angelbroking.com/OpenAPI_File/files/OpenAPIScripMaster.json"
    response = urllib.request.urlopen(instrument_url)
    instrument_list = json.loads(response.read())
    
    token_list = pd.DataFrame(instrument_list)    
    
    token_list.to_csv("angel scripmaster.csv")
    
    print("Token list download completed.")
    

    download_token_list_csv()

    Getting Instrument

    instrument_df = pd.read_csv('angel scripmaster.csv')

    Getting Token No

    def instrument_lookup(instrument=instrument_df,sym='KOTAKBANK'):
    instrument = instrument[(instrument.exch_seg=="NSE")]
    instrument = instrument[instrument['symbol'].str.endswith('-EQ')]
    ## This function used to find instrument token number
    try:
    return instrument[(instrument.name==sym)&(instrument.exch_seg=="NSE")].token.values[0]
    except:
    return -1

    getting symbol name

    def symbol_lookup(instrument=instrument_df,sym='KOTAKBANK'):
    instrument = instrument[(instrument.exch_seg=="NSE")]
    instrument = instrument[instrument['symbol'].str.endswith('-EQ')]
    ## This function used to find instrument symbol name
    try:
    return instrument[(instrument.name==sym)&(instrument.exch_seg=="NSE")].symbol.values[0]
    except:
    return -1

    Streamin Data Starts Here

    AUTH_TOKEN = data['data']['jwtToken']
    API_KEY = kosalauth.apikey
    CLIENT_CODE = kosalauth.clientId
    FEED_TOKEN = smartApi.getfeedToken()

    correlation_id = "abc123"
    action = 1
    mode = 1

    ticker_codes = []
    for ticker in Ticker:
    token = instrument_lookup(instrument=instrument_df, sym=ticker)
    if token != -1:
    ticker_codes.append(token)

    Initialize spot prices dictionary

    spot_prices = {ticker: None for ticker in Ticker}

    Ticker_list to subscribe

    token_list = [{"exchangeType": 1, "tokens": ticker_codes}]

    sws = SmartWebSocketV2(AUTH_TOKEN, API_KEY, CLIENT_CODE, FEED_TOKEN)

    def on_data(wsapp, message):
    #logger.info("Ticks: {}".format(message))
    # Update spot_prices dictionary with the latest last_traded_price
    for ticker in Ticker:
    if 'token' in message and message['token'] == str(instrument_lookup(instrument_df, sym=ticker)):
    spot_prices[ticker] = message.get('last_traded_price')/100

    def on_open(wsapp):
    logger.info("on open")
    sws.subscribe(correlation_id, mode, token_list)

    def on_error(wsapp, error):
    logger.error(error)

    def on_close(wsapp):
    logger.info("Close")

    def close_connection():
    sws.close_connection()

    Assign the callbacks.

    sws.on_open = on_open
    sws.on_data = on_data
    sws.on_error = on_error
    sws.on_close = on_close

    Define the function to run the streaming

    def stream_data():
    sws.connect()

    Define the function to stop streaming and close the connection

    def stop_streaming():
    sws.unsubscribe(correlation_id, mode, token_list)
    close_connection()

    Create threads for streaming and stopping

    stream_thread = threading.Thread(target=stream_data)
    stop_thread = threading.Thread(target=stop_streaming)

    Start the streaming thread

    #stream_thread.start()
    stream_thread.start()

    Algo Start Here

    start =dt.datetime.now(pytz.timezone('Asia/Kolkata'))
    closetime = start.replace(hour=START_TIME[0],minute=START_TIME[1],second=START_TIME[2])
    interval = (closetime-start).total_seconds()
    if interval > 0:
    print('Algo will Run at ',START_TIME[0],':',START_TIME[1],' Remaining Time Left = ',interval,' sec')
    time.sleep(interval)
    print('Algo Starting Now!!!')

    endTime = dt.datetime.now(pytz.timezone('Asia/Kolkata')).replace(hour=EXIT_TIME[0], minute=EXIT_TIME[1],second=EXIT_TIME[2])
    while dt.datetime.now(pytz.timezone('Asia/Kolkata')) <  endTime: 
        
        try:
    
            for i in Ticker:
                 
              
                print("-----------------------------------------------------------------\n")
                print("------------  Angel One Paper Trading Stock Future  -------------\n")
                print("-----------------------------------------------------------------\n")
                print('Spot prices of',i,' ',spot_prices[i]) 
                time.sleep(5)
                
                
        except Exception as e:
            print("Error:",e)
            print("Oops!", e.__class__, "occurred.")
    

    Stop the streaming and close the connection

    stop_thread.start()

    out put coming like this
    C:\Users\sspra\AppData\Local\Temp\ipykernel_516\4065157227.py:1: DtypeWarning: Columns (1) have mixed types. Specify dtype option on import or set low_memory=False.
    instrument_df = pd.read_csv('angel scripmaster.csv')
    [I 240312 16:40:38 4065157227:65] Close
    [I 240312 16:40:38 4065157227:65] Close
    Attempting to resubscribe/reconnect...