I need to open a connection to an API, keep it open and read JSON data incrementally from the open connection. JSON looks like this:
{"type":"PRICE","time":"2020-02-06T16:11:55.724311939Z","bids":[{"price":"1.09730","liquidity":10000000}],"asks":[{"price":"1.09741","liquidity":10000000}],"closeoutBid":"1.09730","closeoutAsk":"1.09741","status":"tradeable","tradeable":true,"instrument":"EUR_USD"}{"type":"PRICE","time":"2020-02-06T16:11:58.619901113Z","bids":[{"price":"1.09731","liquidity":10000000}],"asks":[{"price":"1.09742","liquidity":10000000}],"closeoutBid":"1.09731","closeoutAsk":"1.09742","status":"tradeable","tradeable":true,"instrument":"EUR_USD"}{"type":"PRICE","time":"2020-02-06T16:12:00.095991323Z","bids":[{"price":"1.09730","liquidity":10000000}],"asks":[{"price":"1.09741","liquidity":10000000}],"closeoutBid":"1.09730","closeoutAsk":"1.09741","status":"tradeable","tradeable":true,"instrument":"EUR_USD"}
Every 250mseconds comes a block of data but I am able to read and display only the first block of data, after which I get the error: "Additional text encountered after finished reading JSON content"
The code I have until now:
private async Task IncrementalDeserializeFromStreamCallAsync(CancellationToken cancellationToken)
{
using (var client = new HttpClient())
client.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json"));
client.DefaultRequestHeaders.Add("APP_VERSION", "1.0.0");
client.DefaultRequestHeaders.Authorization = new AuthenticationHeaderValue("Bearer", "tokentokentoken");
using (var request = new HttpRequestMessage(HttpMethod.Get, "https://stream-fxpractice.oanda.com/v3/accounts/101-004-4455670-001/pricing/stream?instruments=EUR_USD"))
using (var response = await client.SendAsync(request, HttpCompletionOption.ResponseHeadersRead, cancellationToken))
{
var stream = await response.Content.ReadAsStreamAsync();
using (StreamReader sr = new StreamReader(stream))
using (JsonTextReader reader = new JsonTextReader(sr))
{
while (reader.Read())
{
if (reader.TokenType == JsonToken.StartObject)
{
// Load each object from the stream and do something with it
JObject obj = JObject.Load(reader);
Console.WriteLine(obj);
}
}
}
}
}