public async Task <Sample> GetCurrentPrice() { if (!connected) { throw new InvalidOperationException("Binance cannot GetCurrentPrice until Initialized!"); } Sample sample = null; do { string json = null; try { json = await websocket.ReceiveMessage(); } catch (WebSocketException e) { Console.WriteLine($"SOCKET ERROR: {e.Message}"); Console.WriteLine("Attempting reconnect and trying again"); await this.websocket.Connect($"wss://stream.binance.com:9443/ws/{tradingPair.ToLower()}@ticker"); continue; } JObject message = JsonConvert.DeserializeObject(json) as JObject; if (message != null && message.ContainsKey("e") && message.GetValue("e").ToString() == "24hrTicker" && message.ContainsKey("b") && decimal.TryParse(message.GetValue("b").ToString(), out decimal price)) { sample = new Sample() { Value = price, DateTime = time.Now }; } else { Console.WriteLine("Got non-ticker/unparseable message:"); Console.WriteLine(message); } } while (sample == null); return(sample); }
private async Task RunWebSocket(IDictionary <string, object> websocketContext) { object value; if (websocketContext.TryGetValue(typeof(WebSocketContext).FullName, out value)) { mWebSocket = new NetWebSocket(((WebSocketContext)value).WebSocket); } else { mWebSocket = new OwinWebSocket(websocketContext); } OnOpen(); await OnOpenAsync(); var buffer = new byte[MaxMessageSize]; Tuple <ArraySegment <byte>, WebSocketMessageType> received = null; do { try { received = await mWebSocket.ReceiveMessage(buffer, mCancellToken.Token); if (received.Item1.Count > 0) { await OnMessageReceived(received.Item1, received.Item2); } } catch (TaskCanceledException) { break; } catch (OperationCanceledException oce) { if (!mCancellToken.IsCancellationRequested) { OnReceiveError(oce); } break; } catch (ObjectDisposedException) { break; } catch (Exception ex) { if (IsFatalSocketException(ex)) { OnReceiveError(ex); } break; } }while (received.Item2 != WebSocketMessageType.Close); try { await mWebSocket.Close(WebSocketCloseStatus.NormalClosure, string.Empty, mCancellToken.Token); } catch { //Ignore } if (!mCancellToken.IsCancellationRequested) { mCancellToken.Cancel(); } OnClose(mWebSocket.CloseStatus, mWebSocket.CloseStatusDescription); await OnCloseAsync(mWebSocket.CloseStatus, mWebSocket.CloseStatusDescription); }