WebSocket Not returning any Tick


  • Hello @Rashmi-Ron

    Here is the code
    from SmartApi.smartWebSocketV2 import SmartWebSocketV2
    from logzero import logger

    AUTH_TOKEN = "Your Auth_Token"
    API_KEY = "Your Api_Key"
    CLIENT_CODE = "Your Client Code"
    FEED_TOKEN = "Your Feed_Token"
    correlation_id = "abc123"
    action = 1
    mode = 1
    token_list = [
        {
            "exchangeType": 1,
            "tokens": ["26009"]
        }
    ]
    #retry_strategy=0 for simple retry mechanism
    sws = SmartWebSocketV2(AUTH_TOKEN, API_KEY, CLIENT_CODE, FEED_TOKEN,max_retry_attempt=2, retry_strategy=0, retry_delay=10, retry_duration=30)
    
    #retry_strategy=1 for exponential retry mechanism
    # sws = SmartWebSocketV2(AUTH_TOKEN, API_KEY, CLIENT_CODE, FEED_TOKEN,max_retry_attempt=3, retry_strategy=1, retry_delay=10,retry_multiplier=2, retry_duration=30)
    
    def on_data(wsapp, message):
        logger.info("Ticks: {}".format(message))
        # close_connection()
    
    def on_control_message(wsapp, message):
        logger.info(f"Control Message: {message}")
    
    def on_open(wsapp):
        logger.info("on open")
        some_error_condition = False
        if some_error_condition:
            error_message = "Simulated error"
            if hasattr(wsapp, 'on_error'):
                wsapp.on_error("Custom Error Type", error_message)
        else:
            sws.subscribe(correlation_id, mode, token_list)
            # sws.unsubscribe(correlation_id, mode, token_list1)
    
    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
    sws.on_control_message = on_control_message
    
    sws.connect()
    

    Regards,
    SmartAPI Team


  • @Moderator_3 can you please re-share the link


  • @Moderator_3 can you please share the link here


  • Hello @Rashmi-Ron

    Can you please check the attached link which is working code

    Regards,
    SamrtAPI Team


  • @admin any update on this??? still not working


  • Not able to run webSocket


  • using System;
    using System.Collections.Generic;
    using System.Linq;
    using System.Text;
    using System.Threading;
    using System.Threading.Tasks;
    using AngelBroking;
    using Newtonsoft.Json;
    using System.IO;
    using System.Data.SqlClient;
    using System.Data;

    namespace AngelBrokingConsoleApp
    {

    class Program
    {
        
    
        internal static int GlobalInt = 0;
      
        //static DataTable tbl = new DataTable();
        internal static SqlBulkCopy objbulk;
        static void Main(string[] args)
        {
            GlobalInt = 0; // FolderCount
            string scriptFiles = System.IO.File.ReadAllText(@"D:\MarketWatch\token\token.txt"); // Reading Tokens from a text file
            string  script = scriptFiles.Replace("\r\n", ""); // Clean the textdata
           
            // - Connection parameters
            string Client_code = "Your Client Code"; 
            string Password = "Your password"; 
            string api_key = "Your API";
            string JWTToken = ""; 
            string RefreshToken = ""; 
            // -End of Connection parameters
    
            SmartApi connect = null;
            OutputBaseClass obj = null;
            AngelBroking.WebSocket _WS = null;
            connect = new SmartApi(api_key, JWTToken, RefreshToken);
            obj = new OutputBaseClass();
            obj = connect.GenerateSession(Client_code, Password);
            AngelToken sagr = obj.TokenResponse;
            obj = connect.GenerateToken();
            sagr = obj.TokenResponse;
            _WS = new AngelBroking.WebSocket();
            var exitEvent = new ManualResetEvent(false);
    
            Console.WriteLine("Connect Socket ");
            _WS.ConnectforStockQuote(sagr.feedToken, Client_code);
    
            if (_WS.IsConnected())
            {
                Console.WriteLine("Connected");
                string TASK = "mw";
                _WS.RunScript(sagr.feedToken, Client_code, script, TASK);
                _WS.MessageReceived += WriteResult;
             }
    
            exitEvent.WaitOne();
    
        }
    
        static void WriteResult(object sender, MessageEventArgs e)
        {
            
            GlobalInt = GlobalInt + 1;  // Increment for the Folder
    
            string fOLDER = System.DateTime.Now.Hour.ToString() + System.DateTime.Now.Minute.ToString(); // Adding Hours and Sec as string
    
            string Folder = @"D:\MarketWatch\Ticks\" + fOLDER; // New Message Writing Folder
            if (!Directory.Exists(Folder)) // Checking need to Create 
            {
                Directory.CreateDirectory(Folder);
            }
            string ProcessFolder = @"D:\MarketWatch\Process\";  
            string myFile = @"D:\MarketWatch\Ticks\" + fOLDER + "\\" + System.DateTime.Now.Second.ToString() + ".txt"; // File Name to write the data
    
            using (StreamWriter sw = File.AppendText(myFile))
            {
    
                var marketData =
               JsonConvert.DeserializeObject<List<RetrieveMultipleResponse>>(e.Message);
    
                for (int i = 0; i < marketData.Count; i++)
                {
                    if (marketData[0].ltp != null)
                    {
                        if (marketData[0].ltt != "NA")
                        {
                            string lineData = marketData[0].ltp + // Last Trade Price
                                        "|" + marketData[0].tk + // Token 
                                        "|" + marketData[0].ltt + // Last trade Time
                                        "|" + marketData[0].tsq + // Total sell Qty
                                        "|" + marketData[0].v + // Voulme
                                        "|" + marketData[0].cng + // Change
                                        "|" + marketData[0].tbq; // Total Buy Qty
                            
                                 
                            sw.WriteLine(lineData);
                           
                           
                            if (GlobalInt >= 60)
                            {
                                try
                                {
                                    ProcessFolder = ProcessFolder + fOLDER; // Writing Flag
                                    FileStream fss = File.Create(ProcessFolder);
                                    GlobalInt = 0;
                                }
                                catch (Exception ex)
                                {
                                    GlobalInt = 0;
    
                                }
                            }
                        }
    
                    }
                }
            }
            Console.WriteLine("Tick Received : " + e.Message);
            //File.WriteAllText(@"D:\xp\a.txt", e.Message);
        }
        public class RetrieveMultipleResponse
        {
            public List<Attribute> Attributes { get; set; }
            public string tvalue { get; set; }
            public string name { get; set; }
            public string to { get; set; }
            public string lo { get; set; }
            public string e { get; set; }
            public string sp { get; set; }
            public string c { get; set; }
            public string ltp { get; set; }
            public string ltq { get; set; }
            public string tk { get; set; }
            public string bs { get; set; }
            public string ltt { get; set; }
            public string tsq { get; set; }
            public string v { get; set; }
            public string bp { get; set; }
            public string cng { get; set; }
            public string bq { get; set; }
            public string ap { get; set; }
            public string nc { get; set; }
            public string tbq { get; set; }
        }
        public class Value
        {
            [JsonProperty("Value")]
            public string value { get; set; }
            public List<string> Values { get; set; }
        }
        public class Attribute
        {
            public string tvalue { get; set; }
            public string name { get; set; }
            public string to { get; set; }
            public string lo { get; set; }
            public string e { get; set; }
            public string sp { get; set; }
            public string c { get; set; }
            public string ltp { get; set; }
            public string ltq { get; set; }
            public string tk { get; set; }
            public string bs { get; set; }
            public string ltt { get; set; }
            public string tsq { get; set; }
            public string v { get; set; }
            public string bp { get; set; }
            public string cng { get; set; }
            public string bq { get; set; }
            public string ap { get; set; }
            public string nc { get; set; }
            public string tbq { get; set; }
        }
    }
    

    }


  • Has this been resolved? Its not working for me too. I am only tying to run the example console app, the 'connect.GetProfile()' is working fine when tested.


  • @admin Any update on this issue?


  • Hi @baluslife our team is working on web socket we will update you once we fix it.