Navigation

    SmartAPI Forum
    • Register
    • Login
    • Search
    • Categories
    • Popular
    • Groups
    • FAQs
    • API Docs

    WebSocket Not returning any Tick

    C#/.Net SDK
    3
    12
    221
    Loading More Posts
    • Oldest to Newest
    • Newest to Oldest
    • Most Votes
    Reply
    • Reply as topic
    Log in to reply
    This topic has been deleted. Only users with topic management privileges can see it.
    • B
      baluslife last edited by

      1)Created new app from "Market Feeds APIs FREE"
      2)Used the following code fro gitHub (Socket Sample Code to get stock quotes Starts Here)
      3) used (script = "nse_cm|2885", TASK = "mw"; )
      Result: _WS.MessageReceived is always null

      help me fix the code.

          public static void test()
          {
              string Client_code = "xxxxx";// YOUR CLIENT CODE
              string Password = "xxxxx";// YOUR PAS SWORD
              string api_key = "xxxxx";// 
              string JWTToken = ""; //optional
              string RefreshToken = ""; //optional
      
              SmartApi connect = new SmartApi(api_key, JWTToken, RefreshToken);
      
              OutputBaseClass obj = new OutputBaseClass();
      
              //Login by client code and password
              obj = connect.GenerateSession(Client_code, Password);
              AngelToken sagr = obj.TokenResponse;
      
              //Get Token
              obj = connect.GenerateToken();
              sagr = obj.TokenResponse;
      
              WebSocket _WS = new WebSocket();
              var exitEvent = new ManualResetEvent(false);
      
              _WS.ConnectforStockQuote(sagr.feedToken, Client_code);
              if (_WS.IsConnected())
              {
                  string script = "nse_cm|2885", TASK = "mw";  // SCRIPT: nse_cm|2885, mcx_fo|222900  TASK: mw|sfi|dp
      
                  _WS.RunScript(sagr.feedToken, Client_code, script, TASK);
                  _WS.MessageReceived += WriteResult;
      
                 // _WS.Close(true);// to stop and close socket connection
              }
              exitEvent.WaitOne();
      
          }
      
          static void WriteResult(object sender, MessageEventArgs e)
          {
              Console.WriteLine("Tick Received");
              Console.WriteLine("Tick Received : " + e.Message);
          }
      
      A 1 Reply Last reply Reply Quote 0
      • A
        admin @baluslife last edited by

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

        B 1 Reply Last reply Reply Quote 0
        • B
          baluslife @admin last edited by

          @admin Any update on this issue?

          R 1 Reply Last reply Reply Quote 0
          • A
            abhi945 last edited by

            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.

            1 Reply Last reply Reply Quote 0
            • R
              ragesh.kv last edited by

              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; }
                  }
              }
              

              }

              1 Reply Last reply Reply Quote 0
              • V
                Vishal.naykawala last edited by

                Not able to run webSocket

                1 Reply Last reply Reply Quote 0
                • R
                  Rashmi Ron @baluslife last edited by

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

                  M 1 Reply Last reply Reply Quote 0
                  • M
                    Moderator_3 @Rashmi Ron last edited by

                    Hello @Rashmi-Ron

                    Can you please check the attached link which is working code

                    Regards,
                    SamrtAPI Team

                    R 2 Replies Last reply Reply Quote 0
                    • R
                      Rashmi Ron @Moderator_3 last edited by

                      @Moderator_3 can you please share the link here

                      1 Reply Last reply Reply Quote 0
                      • R
                        Rashmi Ron @Moderator_3 last edited by

                        @Moderator_3 can you please re-share the link

                        M 1 Reply Last reply Reply Quote 0
                        • M
                          Moderator_3 @Rashmi Ron last edited by

                          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

                          A 1 Reply Last reply Reply Quote 0
                          • A
                            amrutjk @Moderator_3 last edited by

                            @Moderator_3
                            You are sending Python script in C# section ??

                            1 Reply Last reply Reply Quote 0
                            • First post
                              Last post