private void OnReceived(RealtimeReceived receivedMessage) { var order = new BidAskOrder { Id = receivedMessage.OrderId, Price = receivedMessage.Price, Size = receivedMessage.Size }; lock (this._spreadLock) { if (receivedMessage.Side == "buy") { lock (this._bidLock) { this._buys.Add(order); this.Buys = this._buys.ToList(); } } else if (receivedMessage.Side == "sell") { lock (this._askLock) { this._sells.Add(order); this.Sells = this._sells.ToList(); } } } }
private static async void Subscribe(String product, Action <RealtimeMessage> onMessageReceived) { if (String.IsNullOrWhiteSpace(product)) { throw new ArgumentNullException(nameof(product)); } if (onMessageReceived == null) { throw new ArgumentNullException(nameof(onMessageReceived), "Message received callback must not be null."); } var uri = new Uri("wss://ws-feed.exchange.coinbase.com"); var webSocketClient = new ClientWebSocket(); var cancellationToken = new CancellationToken(); var requestString = String.Format(@"{{""type"": ""subscribe"",""product_id"": ""{0}""}}", product); var requestBytes = Encoding.UTF8.GetBytes(requestString); await webSocketClient.ConnectAsync(uri, cancellationToken); if (webSocketClient.State == WebSocketState.Open) { var subscribeRequest = new ArraySegment <Byte>(requestBytes); var sendCancellationToken = new CancellationToken(); await webSocketClient.SendAsync(subscribeRequest, WebSocketMessageType.Text, true, sendCancellationToken); while (webSocketClient.State == WebSocketState.Open) { var receiveCancellationToken = new CancellationToken(); var receiveBuffer = new ArraySegment <Byte>(new Byte[1024 * 1024 * 5]); // 5MB buffer var webSocketReceiveResult = await webSocketClient.ReceiveAsync(receiveBuffer, receiveCancellationToken); if (webSocketReceiveResult.Count == 0) { continue; } var jsonResponse = Encoding.UTF8.GetString(receiveBuffer.Array, 0, webSocketReceiveResult.Count); var jToken = JToken.Parse(jsonResponse); var typeToken = jToken["type"]; if (typeToken == null) { continue; } var type = typeToken.Value <String>(); RealtimeMessage realtimeMessage = null; switch (type) { case "received": realtimeMessage = new RealtimeReceived(jToken); break; case "open": realtimeMessage = new RealtimeOpen(jToken); break; case "done": realtimeMessage = new RealtimeDone(jToken); break; case "match": realtimeMessage = new RealtimeMatch(jToken); break; case "change": realtimeMessage = new RealtimeChange(jToken); break; default: break; } if (realtimeMessage == null) { continue; } onMessageReceived(realtimeMessage); } } }