protected virtual void OnInterpreterProcessedPosition(BitMexWebsocketPosition c) { if (InterpreterProcessedPosition != null) { InterpreterProcessedPosition(this, c); } }
//Update the values of the grid when the object is updated public void UpdatePositionGrid(object source, BitMexWebsocketPosition p) { BindingList <BitMexWebsocketPosition> positions = new BindingList <BitMexWebsocketPosition>(); positions.Add(position); dgdTrades.DataSource = positions.Select(pos => new { Symbol = pos.Symbol, Leverage = pos.Leverage, Side = pos.Side, Size = pos.CurrentQty, AvgEntryPrice = pos.AvgEntryPrice, LiqPrice = pos.LiquidationPrice }).ToList(); }
//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 TRADE subscription //We get rid of the unnecessary part of the string and deserialise the remaining to obtain an object of BitMexWebsocketPosition type //In this case we only want the position for XBTUSD so we specify it in the subscribe message if (message.Contains("\"table\":\"position\"")) { try { string search = "\"data\":"; int i = message.IndexOf(search); string json = message.Substring(i + search.Length); json = json.Remove(json.Length - 1); BitMexWebsocketPosition position = JsonConvert.DeserializeObject <List <BitMexWebsocketPosition> >(json).First(); OnInterpreterProcessedPosition(position); 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(); position = new BitMexWebsocketPosition(); DelegateManagement(); } websocketClient.Connect(); } if (btnConnect.Text == "Disconnect") { websocketClient.Disconnect(); websocketClient = null; } } catch (Exception ex) { ActivityLog.Error("FORM", ex.Message); } }