Help Needed to create code for Ontick Event Handler

DA1077
DA1077 edited October 2017 in .Net API client
Hi,

I have subscribed to KiteConnect API and am trying to get streaming data. I found the sample code for C# application in the official Github link as below:

// Create a new Ticker instance
Ticker ticker = new Ticker(MyAPIKey, MyUserId, MyPublicToken);
// Add handlers to events
ticker.OnTick += onTick;
// Engage reconnection mechanism and connect to ticker
ticker.EnableReconnect(Interval: 5,Retries: 50);
ticker.Connect();
// Subscribing to NIFTY50 and setting mode to LTP
ticker.Subscribe(Tokens: new string[] { "256265" });
ticker.SetMode(Tokens: new string[] { "256265" }, Mode: "ltp");

// Example onTick handler
private static void onTick(Tick TickData)
{
Console.WriteLine("LTP: " + TickData.LastPrice);
}
// Disconnect ticker before closing the application
ticker.Close();

However I am developing the application in Visual Basic and am finding it a bit difficult (Specially the part where Event Handler is added to the Main Class) to replicate the code in VB standard. Will you please help me by providing a sample piece of code for above section.

Thanks,
Amitabha
  • botany02
    botany02 edited October 2017
    Hi,
    Vb equivalent of adding handler.


    AddHandler ticker.OnTick, AddressOf OnTick
  • DA1077
    DA1077 edited October 2017
    Below is my code. Even though Its running fine the msgbox in sub Ontick is not showing anything(Maybe its not getting triggered?). Please suggest how can I fix this issue.

    In Main Class - frmOGGNKite:
    ==========================
    Private Sub btnStartPredefinedProcess_Click(sender As Object, e As EventArgs) Handles btnStartPredefinedProcess.Click
    Dim zerodhainternal As New ZerodhaInternal
    zerodhainternal.tickersubscribeandconnect()
    End Sub

    In Class ZerodhaInternal:
    =======================
    Public WithEvents tickerPredefined As New Ticker(frmOGGNKite.tbxAPIKey.Text, frmOGGNKite.tbxUserID.Text, frmOGGNKite.tbxPublicToken.Text)
    Public Sub tickersubscribeandconnect()
    tickerPredefined.Subscribe(Tokens:={"53461511"})
    tickerPredefined.SetMode(Tokens:={"53461511"}, Mode:="ltp")
    tickerPredefined.Connect()
    End Sub
    Private Sub Ontick(tick As Tick) Handles tickerPredefined.OnTick
    MsgBox(tick)
    End Sub
  • DA1077
    Hi ajinasokan/Sujit,

    Request you to please provide your valuable input to my above code. I am unable to get the streaming data.

    Thanks,
    Amitabha
  • tonystark
    Hi @DA1077,
    Private Sub btnStartPredefinedProcess_Click(sender As Object, e As EventArgs) Handles btnStartPredefinedProcess.Click
    Dim zerodhainternal As New ZerodhaInternal
    zerodhainternal.tickersubscribeandconnect()
    End Sub
    In above snippet, you are creating a new instance of that class inside the subroutine. That object will get destroyed immediately after completing that sub. You have to create the variable outside the sub and instantiate it inside the sub like below:

    Dim zerodhainternal As ZerodhaInternal

    Private Sub btnStartPredefinedProcess_Click(sender As Object, e As EventArgs) Handles btnStartPredefinedProcess.Click
    zerodhainternal = New ZerodhaInternal
    zerodhainternal.tickersubscribeandconnect()
    End Sub
  • tonystark
    Hi @DA1077,

    You can try http://converter.telerik.com/ to get a basic working VB code out of the C# code. This is not guaranteed to work but works most of the time.
  • DA1077
    Hi ajinasokan,

    Thanks for the response. After going through your response I tried to implement my tick receival in the main class itself. My logic is as below:

    1. Automatically Get the access token/public token from the server and populate that in textboxes.(This part is working fine)
    2. When the access token is available initiate the Ticket connection.( Facing problem in this part). If you see blow my code its executing the line "MsgBox("No connection established")" although I can see that Access token/Public Token/UserID is passed properly( Saw that in debug mode ). Please let me know where I a going wrong ?

    My code is as below:

    Public WithEvents tickerPredefined As Ticker
    Dim ConnectionStatus As Boolean

    Private Sub btnStartPredefinedProcess_Click(sender As Object, e As EventArgs) Handles btnStartPredefinedProcess.Click

    Do Until AccessReceived = True
    Loop

    tickerPredefined = New Ticker(tbxAPIKey.Text, tbxUserID.Text, tbxPublicToken.Text)
    tickerPredefined.Subscribe(Tokens:={"53461511"})
    tickerPredefined.SetMode(Tokens:={"53461511"}, Mode:="ltp")
    tickerPredefined.Connect()
    ConnectionStatus = tickerPredefined.IsConnected
    If ConnectionStatus = True Then
    MsgBox("Connection established")
    Else
    MsgBox("No connection established")
    End If
    AddHandler tickerPredefined.OnTick, AddressOf Ontick

    End Sub

    Private Sub Ontick(tick As Tick) Handles tickerPredefined.OnTick
    MsgBox(tick)
    End Sub



    Thanks,
    Amitabha
  • DA1077
    Hi ajinasokan,

    Sorry for making another quick request for your attention to my earlier post. Above section of the code is actually the front section of the logic and until it gets sorted out I am not able to make further development on my application. You expedited response will be of great help.

    Thanks,
    Amitabha
  • tonystark
    tonystark edited October 2017
    Hi @DA1077,

    Our .Net client Ticker implementation is completely non-blocking. It is asynchronous. This means every function call to Ticker will execute immediately and will not wait for the network to respond. If there are any issues they will be reported via OnError event. This is for not wasting time on waiting for the network to respond.

    In your implementation tickerPredefined.Connect() will ask ticker to connect to the server which will take a few milliseconds. But the function execution will complete immediately and will go to the next line of your code which is ConnectionStatus = tickerPredefined.IsConnected. Until server connection is complete tickerPredefined.IsConnected will return False. That is why you are getting that message. Try attaching OnConnect event to your ticker object.

    I suggest you go through the example code once again. Also, since you are using Winforms you can create multiple buttons for Create Ticker, Connect, Subscribe, UnSubscribe, Close and do appropriate actions for understanding the event mechanism.

    Also, I would like to mention that you are creating new Ticker connections in a loop which is a bad idea since this is based on events.
  • DA1077
    DA1077 edited October 2017
    Hi ajinasokan,

    I followed as per your suggestion but still the connection is not getting active. I am struggling to get through this opening piece of code for last one week. Will you please recreate the scenario at your end using below code and let me know what's wrong here ? My current code is provided below. I have created a separate button Button1 to check if the connection is up or not. I am getting the message "No connection established" even when I click Button1. Note that the values in the textboxes tbxAPIKey.Text, tbxUserID.Text, tbxPublicToken.Text are correctly populated and no exception error is received at any step. Request you to please recreate this small scenario at your end and provide your expert advise on this.

    Code:
    ======
       Public WithEvents tickerPredefined As Ticker
    Dim ConnectionStatus As Boolean

    Private Sub btnStartPredefinedProcess_Click(sender As Object, e As EventArgs) Handles btnStartPredefinedProcess.Click
    tickerPredefined = New Ticker(tbxAPIKey.Text, tbxUserID.Text, tbxPublicToken.Text)
    AddHandler tickerPredefined.OnTick, AddressOf Ontick
    AddHandler tickerPredefined.OnConnect, AddressOf Onconnect
    tickerPredefined.Connect()
    MsgBox("Connection step executed")
    End Sub

    Private Sub Ontick(tick As Tick) Handles tickerPredefined.OnTick
    MsgBox(tick)
    End Sub
    Private Sub Onconnect() Handles tickerPredefined.OnConnect
    ConnectionStatus = tickerPredefined.IsConnected
    If ConnectionStatus = True Then
    MsgBox("Connection established")
    Else
    MsgBox("No connection established")
    End If
    End Sub

    Private Sub Button1_Click(sender As Object, e As EventArgs) Handles Button1.Click
    tickerPredefined.Subscribe(Tokens:={"53471751"})
    tickerPredefined.SetMode(Tokens:={"53471751"}, Mode:="ltp")
    ConnectionStatus = tickerPredefined.IsConnected
    If ConnectionStatus = True Then
    MsgBox("Connection established")
    Else
    MsgBox("No connection established")
    End If
    End Sub
    Thanks,
    Amitabha
  • DA1077
    Request to please provide your response.
  • tonystark
    tonystark edited October 2017
    Hi @DA1077,

    Here is an example:
    Imports KiteConnect

    Public Class frmMain

    WithEvents ticker As Ticker

    Private Sub btnBuild_Click(sender As Object, e As EventArgs) Handles btnBuild.Click
    ticker = New Ticker("apikey", "userid", "publickey")

    AddHandler ticker.OnConnect, AddressOf OnConnect
    AddHandler ticker.OnTick, AddressOf OnTick
    AddHandler ticker.OnClose, AddressOf OnClose

    txtLog.AppendText("Ticker created" + vbCrLf)
    End Sub

    Private Sub btnConnect_Click(sender As Object, e As EventArgs) Handles btnConnect.Click
    ticker.Connect()
    End Sub

    Private Sub btnSubscribe_Click(sender As Object, e As EventArgs) Handles btnSubscribe.Click
    ticker.Subscribe(Tokens:={"256265"})
    ticker.SetMode(Tokens:={"256265"}, Mode:="ltp")
    txtLog.AppendText("Subscribed" + vbCrLf)
    End Sub

    Private Sub btnDisconnect_Click(sender As Object, e As EventArgs) Handles btnDisconnect.Click
    ticker.Close()
    End Sub

    Sub OnConnect()
    txtLog.AppendText("Connected" + vbCrLf)
    End Sub

    Sub OnTick(tick As Tick)
    If InvokeRequired Then 'Because ticker is in a different thread'
    Invoke(Sub()
    txtLog.AppendText("LTP: " + tick.LastPrice.ToString() + vbCrLf)
    End Sub)
    Else
    txtLog.AppendText("LTP: " + tick.LastPrice.ToString() + vbCrLf)
    End If
    End Sub

    Sub OnClose()
    txtLog.AppendText("Closed" + vbCrLf)
    End Sub

    End Class
  • DA1077
    I tried above code and still was getting same issue as I was facing earlier. Later I added Onerror module to trap any error and found below issue during when connecting. The error message received is == >
    Error While connecting. Message: The Websocket protocol is not supported on this platform.
    I am using Visual Studio 2017 Community version 15.4.0 and .NET Framework Version 4.7.02053.

    Please suggest is there is any compatibility issue here or something else.
  • tonystark
    Hi @DA1077,

    Which OS are you using?
  • DA1077
    Windows 7
  • tonystark
    tonystark edited October 2017
    Hi @DA1077,

    Unfortunately, WebSocket feature that comes with .Net framework is not supported on Windows 7 and earlier. And there is no update or patch for this in Windows 7 since Microsoft stopped the support for it.

    If you have to use Win 7 you will have to use third-party client libraries for Kite Connect. But recommended approach is to use latest Windows version with updates.
  • DA1077
    Hi ajinasokan,

    Thanks for your time and the update. I will try on a different machine having Windows 10.

    Thanks,
    Amitabha
This discussion has been closed.