protected virtual void OnInterpreterProcessedQuote(BitMexWebsocketQuote c) { if (InterpreterProcessedQuote != null) { InterpreterProcessedQuote(this, c); } }
//ProcessMessage is called every time a message is received from the Websocket, here the message is interpreted and directed to the correct function public void ProcessMessage(object source, string message) { //The Websocket message contains an update regarding the QUOTE subscription //We get rid of the unnecessary part of the string and deserialise the remaining to obtain an object of BitMexWebsocketQuote type //We then pass the call another event to update the object through a Delegate //Note that the websocket message can contain several quotes at the same time so what we do is deserialize to a list and only keep the last //because the last is the most recent if (message.Contains("\"table\":\"quote\"")) { try { string search = "\"data\":"; int i = message.IndexOf(search); string json = message.Substring(i + search.Length); json = json.Remove(json.Length - 1); BitMexWebsocketQuote quote = JsonConvert.DeserializeObject <List <BitMexWebsocketQuote> >(json).Last(); OnInterpreterProcessedQuote(quote); return; } catch (Exception e) { ActivityLog.Error("WEBSOCKET INTERPRETER", e.Message); } } //We add this check so that we do not log API Keys in plain text in the log file if (message.Contains("error") && !message.Contains("authKey")) { ActivityLog.Error("WEBSOCKET INTERPRETER", message); return; } //We add this check so that we do not log API Keys in plain text in the log file if (message.Contains("error") && message.Contains("authKey")) { ActivityLog.Error("WEBSOCKET INTERPRETER", "Authentication Failed, Please Check API Keys"); return; } }
//When we try to connect to the websocket the objects are instantiated private void btnConnect_Click(object sender, EventArgs e) { try { if (btnConnect.Text == "Connect") { if (cboWebsocketURL.SelectedIndex != 1 && cboWebsocketURL.SelectedIndex != 0) { return; } string apiKey = ""; string apiSecret = ""; if (websocketClient == null || !websocketClient.GetIsConnected()) { if (chkAuthenticate.Checked) { apiKey = txtAPIKey.Text; apiSecret = txtAPISecret.Text; } websocketClient = new BitMexWebsocketClient(new Uri(cboWebsocketURL.Text), apiKey, apiSecret); websocketInterpreter = new BitMexWebsocketInterpreter(); quote = new BitMexWebsocketQuote(); DelegateManagement(); } websocketClient.Connect(); } if (btnConnect.Text == "Disconnect") { websocketClient.Disconnect(); websocketClient = null; } } catch (Exception ex) { ActivityLog.Error("FORM", ex.Message); } }
//Update the values of the Textboxes when the object is updated //Note that quote also contains Symbol and Size of Bid and Ask however we are not using them in this example public void UpdateQuoteValues(object source, BitMexWebsocketQuote c) { txtAsk.Text = quote.AskPrice.ToString(); txtBid.Text = quote.BidPrice.ToString(); }